Introduction to sessions
A session is used to store information related to a user, across different requests, as they interact with a web app. The data stored for a session should be considered temporary data, as the session will eventually expire. In order to permanently store date, you need to utilise a database.
Flask uses the client-side approach where sessions are stored in browser cookies. This cookie is sent with each request to the Flask app on the server-side where it's decoded.
Pros:
Validating and creating sessions is fast (no data storage)
Easy to scale (no need to replicate session data across web servers)
Cons:
Sensitive data cannot be stored in session data, as it's stored on the web browser
Session data is limited by the size of the cookie (usually 4 KB)
Sessions cannot be immediately revoked by the Flask app
Session Life
By default, the session
object remains in place until the browser is closed. However, if you want to change the life of the session
object, define the PERMANENT_SESSION_LIFETIME configuration variable after creating the Flask app
:
When setting the data in the session
, specify that the sessions should be permanent (time will be based on PERMANENT_SESSION_LIFETIME
):
References
Last updated
Was this helpful?