File size: 1,205 Bytes
2f3c093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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