Last active
April 7, 2023 07:07
-
-
Save TheBigRoomXXL/31f6676e0220627df0a603f954f8ee4f to your computer and use it in GitHub Desktop.
SQL Cursor for Flask-SQLAlchemy and Flask-Smorest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask.views import MethodView | |
from flask_smorest import Blueprint | |
from commons import db, SQLCursor | |
from models.book import Book, Bookshema | |
blp = Blueprint( | |
"books", "books", url_prefix="/books", description="Operations on books" | |
) | |
@blp.route("/") | |
class BookListRessource(MethodView): | |
@blp.arguments(BookFiltersSchema(partial=True), location="querystring") | |
@blp.response(200, BookSchema(many=True)) | |
@blp.paginate(SQLCursor) | |
def get(self, filters): | |
"""List books""" | |
return Book.query.filter_by(**filters).order_by(Book.name) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask_smorest import Api, Blueprint | |
from flask_sqlalchemy.query import Query | |
class SQLCursor(): | |
"""Automatically paginate a Query object return by a view""" | |
def __init__(self, query:Query, page_params): | |
self.page_params = page_params | |
self.result = query.paginate( | |
page=page_params.page, | |
per_page=page_params.page_size, | |
max_per_page=None, #Change it if user must use pagination | |
error_out=False, | |
count=True | |
) | |
self.page_params.item_count = self.item_count | |
@property | |
def items(self): | |
return self.result.items | |
@property | |
def item_count(self): | |
return self.result.total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment