Guest User

Untitled

a guest
Oct 16th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. from chalice import Response
  2. from cerberus import Validator
  3.  
  4.  
  5. def validate(schema, location="body"):
  6. def decorator(fn):
  7. def wrapped_f(*args, **kwargs):
  8. v = Validator(schema, allow_unknown=True)
  9. data = {}
  10.  
  11. if location == "body":
  12. data = app.current_request.json_body or data
  13. if location == "query":
  14. data = app.current_request.query_params or data
  15.  
  16. if v(data):
  17. return fn(*args, **kwargs)
  18.  
  19. body = {"message": f"Invalid {location} parameters.", "data": v.errors}
  20. return Response(body=body, status_code=400)
  21.  
  22.  
  23. """
  24. # Sample usage:
  25.  
  26. todo_list_params = {
  27. "keyword": {"type": "string", "required": False, "empty": False},
  28. "start_date": {"type": "datetime", "required": False, "empty": False,
  29. "coerce": lambda date: datetime.datetime.strptime(date, "%Y-%m-%d")},
  30. }
  31.  
  32. @app.route("/todos", methods=["GET"])
  33. @validate(todo_list_params, location="query")
  34. def get_todo_list():
  35. return {"todos": []}
  36. """
Add Comment
Please, Sign In to add comment