Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
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)
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 " \
warnings.warn(msg, Warning, 2)
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
Something went wrong with that request. Please try again.