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

45 lines
1.2 KiB
Python
Raw Normal View History

from typing import TypedDict, Tuple
from flask import current_app
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
}
def is_allowed_extensions(filename: str):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS']