58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
from flask import request
|
|
from functools import wraps
|
|
from marshmallow import ValidationError
|
|
from app.common.responses import error_response
|
|
|
|
|
|
def validate_request(schema_class):
|
|
"""
|
|
Decorator to validate incoming JSON request data against a marshmallow schema.
|
|
|
|
Usage:
|
|
@customer.route("/create", methods=["POST"])
|
|
@validate_request(CreateCustomerSchema)
|
|
def create_customer():
|
|
data = request.validated_data # Access validated data
|
|
...
|
|
"""
|
|
def decorator(f):
|
|
@wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
# Check if request has JSON data
|
|
if not request.is_json:
|
|
return error_response("Request must be JSON", 400)
|
|
|
|
json_data = request.get_json()
|
|
if json_data is None:
|
|
return error_response("Invalid JSON data", 400)
|
|
|
|
# Validate the data
|
|
schema = schema_class()
|
|
try:
|
|
validated_data = schema.load(json_data)
|
|
# Attach validated data to request object for easy access
|
|
request.validated_data = validated_data
|
|
except ValidationError as err:
|
|
return error_response("Validation failed", 400, details=str(err.messages))
|
|
|
|
return f(*args, **kwargs)
|
|
return decorated_function
|
|
return decorator
|
|
|
|
|
|
def validate_json(schema_class, data):
|
|
"""
|
|
Validate data against a schema and return (validated_data, errors).
|
|
|
|
Usage:
|
|
data, errors = validate_json(CreateCustomerSchema, request.get_json())
|
|
if errors:
|
|
return jsonify({"error": "Validation failed", "details": errors}), 400
|
|
"""
|
|
schema = schema_class()
|
|
try:
|
|
validated_data = schema.load(data or {})
|
|
return validated_data, None
|
|
except ValidationError as err:
|
|
return None, err.messages
|