59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
from fastapi import status
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
|
def return_json_response_from_alchemy(
|
|
response, cls_obj=None, pagination=None, response_model=None
|
|
):
|
|
enums = cls_obj.__enums__ if cls_obj else []
|
|
if response.count:
|
|
total_count = response.query.limit(None).offset(None).count()
|
|
total_page_number = round(total_count / int(pagination.size), 0) + 1
|
|
pagination_dict = {
|
|
"size/total_count": [response.count, total_count],
|
|
"page/total_page": [pagination.page, total_page_number],
|
|
"order_field": pagination.order_field,
|
|
"order_type": pagination.order_type,
|
|
}
|
|
include_joins = dict(
|
|
include_joins=pagination.include_joins if pagination.include_joins else None
|
|
)
|
|
|
|
if not isinstance(response.data[0], dict):
|
|
data = []
|
|
for obj in response.data:
|
|
data_object = obj.get_dict(**include_joins)
|
|
if response_model:
|
|
data_object = response_model(
|
|
**obj.get_dict(**include_joins)
|
|
).model_dump()
|
|
data.append(data_object)
|
|
else:
|
|
data = []
|
|
for obj in response.data:
|
|
data_object = obj
|
|
if response_model:
|
|
data_object = response_model(**obj).model_dump()
|
|
data.append(data_object)
|
|
|
|
return JSONResponse(
|
|
status_code=status.HTTP_200_OK,
|
|
content=dict(
|
|
pagination=pagination_dict,
|
|
message="Found records are listed",
|
|
completed=True,
|
|
data=data,
|
|
),
|
|
)
|
|
|
|
return JSONResponse(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
content=dict(
|
|
total_count=0,
|
|
count=0,
|
|
message="No record has found",
|
|
completed=False,
|
|
data=[],
|
|
),
|
|
)
|