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

41 lines
1.1 KiB
Python
Raw Normal View History

from typing import TypedDict, Union
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: Union[str, None]
) -> 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: int, query: BaseQuery, per_page=10) -> PaginationResponse:
default_page = 1
if page is not None:
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"]
)