Book Image

Mastering Flask

By : Jack Stouffer
Book Image

Mastering Flask

By: Jack Stouffer

Overview of this book

Starting from a simple Flask app, this book will walk through advanced topics while providing practical examples of the lessons learned. After building a simple Flask app, a proper app structure is demonstrated by transforming the app to use a Model-View-Controller (MVC) architecture. With a scalable structure in hand, the next chapters use Flask extensions to provide extra functionality to the app, including user login and registration, NoSQL querying, a REST API, an admin interface, and more. Next, you’ll discover how to use unit testing to take the guesswork away from making sure the code is performing as it should. The book closes with a discussion of the different platforms that are available to deploy a Flask app on, the pros and cons of each one, and how to deploy on each one.
Table of Contents (20 chapters)
Mastering Flask
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Request setup, teardown, and application globals


In some cases, a request-specific variable is needed across all view functions and needs to be accessed from the template as well. To achieve this, we can use Flask's decorator function @app.before_request and the object g. The function @app.before_request is executed every time before a new request is made. The Flask object g is a thread-safe store of any data that needs to be kept for each specific request. At the end of the request, the object is destroyed, and a new object is spawned at the start of a new request. For example, the following code checks whether the Flask session variable contains an entry for a logged in user; if it exists, it adds the User object to g:

from flask import g, session, abort, render_template

@app.before_request
def before_request():
    if ‘user_id’ in session:
        g.user = User.query.get(session[‘user_id’])

@app.route(‘/restricted’)
def admin():
    if g.user is None:
        abort(403)
    return render_template...