Permalink
Browse files

add decorator for returning JSON from views

  • Loading branch information...
axitkhurana committed May 29, 2012
1 parent 48cb6a7 commit 2c5cb34a83205233ec65a193f650db7ff512323b
Showing with 26 additions and 0 deletions.
  1. +26 −0 popcorn/helpers.py
View
@@ -0,0 +1,26 @@
from functools import wraps
from flask import request, jsonify, render_template
def request_wants_json():
best = request.accept_mimetypes.best_match(['application/json',
'text/html'])
return best == 'application/json' and (request.accept_mimetypes[best] >
request.accept_mimetypes['text/html'])
def render(template=None):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
ctx = f(*args, **kwargs)
if ctx is None:
ctx = {}
elif not isinstance(ctx, dict):
return ctx
render_type = request_wants_json()
if render_type:
return jsonify(ctx)
return render_template(template, **ctx)
return decorated_function
return decorator

0 comments on commit 2c5cb34

Please sign in to comment.