2022-10-26 10:33:35 +02:00
|
|
|
from typing import TypedDict, Union
|
2022-05-18 17:36:16 +02:00
|
|
|
|
2022-10-26 10:33:35 +02:00
|
|
|
from flask import current_app
|
2022-05-18 17:36:16 +02:00
|
|
|
from flask_sqlalchemy import BaseQuery
|
|
|
|
from sqlalchemy import desc
|
|
|
|
|
|
|
|
|
|
|
|
class PaginationResponse(TypedDict):
|
|
|
|
items: list
|
|
|
|
max_pages: int
|
|
|
|
|
|
|
|
|
2023-01-14 17:38:03 +01:00
|
|
|
def order_by_column_name(
|
|
|
|
query: BaseQuery, model_field: str, order_by_col_name: Union[str, None]
|
|
|
|
) -> BaseQuery:
|
2022-05-18 17:36:16 +02:00
|
|
|
if order_by_col_name is not None:
|
2023-01-14 17:38:03 +01:00
|
|
|
if order_by_col_name == "asc":
|
2022-05-18 17:36:16 +02:00
|
|
|
query = query.order_by(model_field)
|
2023-01-14 17:38:03 +01:00
|
|
|
elif order_by_col_name == "desc":
|
2022-05-18 17:36:16 +02:00
|
|
|
query = query.order_by(desc(model_field))
|
|
|
|
|
|
|
|
return query
|
|
|
|
|
|
|
|
|
2022-06-13 18:04:30 +02:00
|
|
|
def paginate_models(page: int, query: BaseQuery, per_page=10) -> PaginationResponse:
|
2022-05-18 17:36:16 +02:00
|
|
|
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)
|
|
|
|
|
2023-01-14 17:38:03 +01:00
|
|
|
return {"items": query.items, "max_pages": query.pages}
|
2022-05-19 18:15:11 +02:00
|
|
|
|
|
|
|
|
|
|
|
def is_allowed_extensions(filename: str):
|
2023-01-14 17:38:03 +01:00
|
|
|
return (
|
|
|
|
"." in filename
|
|
|
|
and filename.rsplit(".", 1)[1].lower()
|
|
|
|
in current_app.config["ALLOWED_EXTENSIONS"]
|
|
|
|
)
|