38 lines
960 B
Python
38 lines
960 B
Python
from functools import wraps
|
|
|
|
from flask import jsonify
|
|
|
|
|
|
def serialize_response(model):
|
|
"""Decorator to serialize single entity response"""
|
|
|
|
def decorator(f):
|
|
@wraps(f)
|
|
def wrapper(*args, **kwargs):
|
|
result, status = f(*args, **kwargs)
|
|
if status not in [200, 201]:
|
|
return result, status
|
|
return jsonify(model.model_validate(result).model_dump()), status
|
|
|
|
return wrapper
|
|
|
|
return decorator
|
|
|
|
|
|
def serialize_list_response(model):
|
|
"""Decorator to serialize list response"""
|
|
|
|
def decorator(f):
|
|
@wraps(f)
|
|
def wrapper(*args, **kwargs):
|
|
results, status = f(*args, **kwargs)
|
|
if status not in [200, 201]:
|
|
return results, status
|
|
return (
|
|
jsonify([model.model_validate(item).model_dump() for item in results]),
|
|
status,
|
|
)
|
|
|
|
return wrapper
|
|
|
|
return decorator
|