Template or JSON decorator for Flask

Write your view function to return a context that will either be serialized as JSON or used as the template context.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def template_or_json(template=None):
    """"Return a dict from your view and this will either 
    pass it to a template or render json. Use like:
 
    @template_or_json('template.html')
 
    """
    def decorated(f):
        @wraps(f)
        def decorated_fn(*args, **kwargs):
            ctx = f(*args, **kwargs)
            if request.is_xhr or not template:
                return jsonify(ctx)
            else:
                return render_template(template, **ctx)
        return decorated_fn
    return decorated

Usage:

1
2
3
4
@app.route('/', methods=['GET'])
@template_or_json('template.html')
def example():
    return { "foo": "bar" }

2013-08-04