dia-gov's picture
Upload 102 files
2f3c093 verified
Raw History Blame Contribute Delete
1.21 kB
from functools import wraps
from flask import request, jsonify
from typing import Callable, Type
from marshmallow import Schema, ValidationError
def validate_input(serializer: Type[Schema], partial: bool = False) -> Callable:
"""
Validates the input data using a Marshmallow serializer.
Args:
serializer (Type[Schema]): The Marshmallow serializer to use.
partial (bool, optional): Whether to allow partial updates. Defaults to False.
Returns:
Callable: The decorated function.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
data = request.get_json()
if not data:
return jsonify({'error': 'No input data provided'}), 400
deserialized_data = serializer().load(data, partial=partial)
request.deserialized_data = deserialized_data
return func(*args, **kwargs)
except ValidationError as e:
return jsonify({'error': str(e)}), 400
except Exception as e:
return jsonify({'error': 'Invalid input data'}), 400
return wrapper
return decorator