Skip to content

Instantly share code, notes, and snippets.

@EnigmaCurry
Created September 20, 2010 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EnigmaCurry/587952 to your computer and use it in GitHub Desktop.
Save EnigmaCurry/587952 to your computer and use it in GitHub Desktop.
Pylons jsonify decorator
# 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment