Decorator to handle requests beautifully
Some of us might think that checking whether a request is XHR or not every time kills code readability. To solve this, we have an easy solution. We can just write a simple decorator that will handle this redundant code for us.
Getting ready
In this recipe, we will be writing a decorator. For some of the beginners in Python, this might seem like alien territory. In this case, read http://legacy.python.org/dev/peps/pep-0318/ for a better understanding of decorators.
How to do it…
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: ...