system-pri/backend/app/base/utils.py

39 lines
1.1 KiB
Python

from typing import TypedDict, Tuple
from flask_sqlalchemy import BaseQuery
from sqlalchemy import desc
class PaginationResponse(TypedDict):
items: list
max_pages: int
def order_by_column_name(query: BaseQuery, model_field: str, order_by_col_name: str) -> BaseQuery:
if order_by_col_name is not None:
if order_by_col_name == 'asc':
query = query.order_by(model_field)
elif order_by_col_name == 'desc':
query = query.order_by(desc(model_field))
return query
def paginate_models(page: str, query: BaseQuery) -> PaginationResponse or Tuple[dict, int]:
per_page = 10
default_page = 1
if page is not None:
try:
page = int(page)
except ValueError:
return {"error": f"Invalid page! Page must be integer!"}, 400
query = query.paginate(page=page, per_page=per_page, error_out=False)
else:
query = query.paginate(page=default_page, per_page=per_page, error_out=False)
return {
'items': query.items,
'max_pages': query.pages
}