July 2019
Beginner to intermediate
302 pages
9h 38m
English
The following is the decorator method that we have written for this recipe:
from functools import wraps
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
This decorator simply does what we did in the previous recipe to handle XHR; that is, checking whether our request is XHR and, based on the outcome, either rendering the template or returning JSON data.
Now, let's apply this ...