Created
September 20, 2010 14:07
-
-
Save EnigmaCurry/587952 to your computer and use it in GitHub Desktop.
Pylons jsonify decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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