codejunky

Untitled

Apr 5th, 2015
681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. def json(f):
  2.     """Generate a JSON response from a database model or a Python
  3.    dictionary."""
  4.     @functools.wraps(f)
  5.     def wrapped(*args, **kwargs):
  6.         # invoke the wrapped function
  7.         rv = f(*args, **kwargs)
  8.  
  9.         # the wrapped function can return the dictionary alone,
  10.         # or can also include a status code and/or headers.
  11.         # here we separate all these items
  12.         status = None
  13.         headers = None
  14.         if isinstance(rv, tuple):
  15.             rv, status, headers = rv + (None,) * (3 - len(rv))
  16.         if isinstance(status, (dict, list)):
  17.             headers, status = status, None
  18.  
  19.         # if the response was a database model, then convert it to a
  20.         # dictionary
  21.         if not isinstance(rv, dict):
  22.             rv = rv.export_data()
  23.  
  24.         # generate the JSON response
  25.         rv = jsonify(rv)
  26.         if status is not None:
  27.             rv.status_code = status
  28.         if headers is not None:
  29.             rv.headers.extend(headers)
  30.         return rv
  31.     return wrapped
Add Comment
Please, Sign In to add comment