2022-05-18 17:36:16 +02:00
|
|
|
from typing import TypedDict, Tuple
|
|
|
|
|
2022-05-19 18:15:11 +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
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2022-05-19 18:15:11 +02:00
|
|
|
|
|
|
|
|
|
|
|
def is_allowed_extensions(filename: str):
|
|
|
|
return '.' in filename and \
|
|
|
|
filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS']
|