major claude changes
This commit is contained in:
56
app/schemas/utils.py
Normal file
56
app/schemas/utils.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from flask import jsonify, request
|
||||
from functools import wraps
|
||||
from marshmallow import ValidationError
|
||||
|
||||
|
||||
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 jsonify({"error": "Request must be JSON"}), 400
|
||||
|
||||
json_data = request.get_json()
|
||||
if json_data is None:
|
||||
return jsonify({"error": "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 jsonify({"error": "Validation failed", "details": err.messages}), 400
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user