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 ...

Get Flask Framework Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.