Book Image

Learning Flask Framework

Book Image

Learning Flask Framework

Overview of this book

Table of Contents (17 chapters)
Learning Flask Framework
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Sessions


As you've worked through this chapter, you may have wondered how Flask-Login (and also Flask) are able to determine which user is logged in between requests, request after request. Flask-Login does this by storing a user's ID in a special object called the session. Sessions utilize cookies to securely store morsels of information. When the user makes a request to your Flask application, their cookies are sent along with the request, and Flask is able to inspect the cookie data and load it into the session object. Similarly, your views can add or modify information stored in the session, updating the user's cookies in the process.

The beauty of Flask's session object is that it can be used for any visitor to the site, whether they are logged in or not. The session can be treated just like an ordinary Python dictionary. The following code shows how you might track the last page a user visited using the session:

from flask import request, session

@app.before_request
def _last_page_visited...