public
Last active

Pylons jsonify decorator

  • Download Gist
pylons_jsonify.py
Python
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 34 35 36 37
# A fixed @jsonify decorator for Pylons that allows for
# class implemented __json__ serializers
 
from decorator import decorator
from pylons.decorators.util import get_pylons
import warnings
import json
import logging
 
log = logging.getLogger(__name__)
 
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
encoder = getattr(obj, '__json__', None)
if encoder: return encoder()
return super(JSONEncoder, self).default(obj)
 
@decorator
def jsonify(func, *args, **kwargs):
"""Action decorator that formats output for JSON
 
Given a function that will return content, this decorator will turn
the result into JSON, with a content-type of 'application/json' and
output it.
 
"""
pylons = get_pylons(args)
pylons.response.headers['Content-Type'] = 'application/json'
data = func(*args, **kwargs)
if isinstance(data, (list, tuple)):
msg = "JSON responses with Array envelopes are susceptible to " \
"cross-site data leak attacks, see " \
"http://pylonshq.com/warnings/JSONArray"
warnings.warn(msg, Warning, 2)
log.warning(msg)
log.debug("Returning JSON wrapped action output")
return json.dumps(data,cls=JSONEncoder)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.