Skip to Content
Flask Framework Cookbook - Second Edition
book

Flask Framework Cookbook - Second Edition

by Shalabh Aggarwal
July 2019
Beginner to intermediate
302 pages
9h 38m
English
Packt Publishing
Content preview from Flask Framework Cookbook - Second Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Writing a Web Application with Flask

Writing a Web Application with Flask

Doug Farrell
Mastering Flask

Mastering Flask

Jack Stouffer

Publisher Resources

ISBN: 9781789951295Supplemental Content