Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Flask Framework Cookbook

You're reading from   Flask Framework Cookbook Over 80 hands-on recipes to help you create small-to-large web applications using Flask

Arrow left icon
Product type Paperback
Published in Nov 2014
Publisher
ISBN-13 9781783983407
Length 258 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Shalabh Aggarwal Shalabh Aggarwal
Author Profile Icon Shalabh Aggarwal
Shalabh Aggarwal
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Flask Configurations FREE CHAPTER 2. Templating with Jinja2 3. Data Modeling in Flask 4. Working with Views 5. Webforms with WTForms 6. Authenticating in Flask 7. RESTful API Building 8. Admin Interface for Flask Apps 9. Internationalization and Localization 10. Debugging, Error Handling, and Testing 11. Deployment and Post Deployment 12. Other Tips and Tricks Index

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:
              ...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime