Managing User Sessions and Cookies

Share:

In this guide, we will explore how to manage user sessions and cookies in Flask. User sessions are integral in maintaining a connection between the user and the server, and cookies allow us to recall specific user preferences and state across multiple requests. Authentication and identification of the user are usually done by using sessions.

Let us first examine what sessions mean in the context of web applications.

Understanding Sessions

A session is a space in server memory--or an external database, usually filled with user-specific data. In different scenarios, sessions manifest as shopping carts for internet marketplaces, login credentials for web applications, or user preferences for site-wide themes. For our tutorial, think of sessions as a director's selection of movie genres.

Now, let's take a look at how we implement sessions in Flask:

from flask import [Flask](https://stackbay.org/modules/learn-flask), session

app = [Flask](https://stackbay.org/modules/learn-flask)(__name__)
app.secret_key = 'TopSecretKey' 

@app.route('/')
def index():
   return "Welcome to the Movie Database!"

@app.route('/fav/movie', methods=['POST'])
def fav_movie():
   session['FavMovie'] = request.form['movie']
   return "Movie added to the list!"

@app.route('/get/movie')
def get_movie():
   return "Your favorite movie is {}".format(session.get('FavMovie', 'None'))
   

Here, we've initialized the session object from Flask in our application. The secret key is important as Flask uses it to sign the session. It should ideally be a complex string that is hard to guess. In our example, when a post request is made to '/fav/movie', we store the favorite movie into the session. We later fetch it using the 'get' method on the session object.

Understanding Cookies

Cookies are a more simple and less secure way of storing user data than sessions. Cookies store data on the client-side, while sessions store data on the server-side. But cookies do have their uses. They are invaluable in remembering user activity across web pages.

Imagine you're scrolling through a movie archive website. When you press the back button, the website remembers exactly where you were. This is done using cookies. Your last location is stored in a cookie and assembled when needed.

Here's how you can set a cookie in Flask:

@app.route('/')
def index():
   resp = make_response("Welcome to the Movie Database!")
   resp.set_cookie('lastMovieSeen', 'Fight Club')
   return resp

In this code snippet, we first make a response object. We call the set_cookie method to add a cookie to the response. In this case, it's the 'lastMovieSeen' cookie.

Just like we can set a cookie, we can also get the value of a cookie:

@app.route('/get/movie')
def get_movie():
   movie = request.cookies.get('lastMovieSeen')
   return "The last movie you saw was {}".format(movie)

Here we retrieve the 'lastMovieSeen' cookie's value and return it as a message onto the screen.

Deleting Sessions and Cookies

There will always be circumstances where you need to delete a session or a cookie. We do this when the user logs out of their account or when their session expires.

Sessions in Flask are easily cleared with the clear or pop functions. The clear function removes all keys in a session, while the pop function removes a given key.

Here is an example:

@app.route('/logout')
def logout():
   # Remove the username from the session
   session.pop('username', None)
   return redirect(url_for('index'))

In the code snippet above, we remove the 'username' from the session. If the 'username' key doesn't exist, the pop function returns None, allowing the application not to crash with a KeyError.

Deleting cookies is a little more complex. Unlike sessions, you can't outright delete a cookie. Instead, we set its expiry time to a past date, thus expiring the cookie.

Here's a representation:

@app.route('/logout')
def logout():
   resp = make_response(redirect(url_for('index')))
   resp.set_cookie('sessionId', '', expires=0)
   return resp

In the above snippet, we create a response object, then set an expiration date for the 'sessionId' cookie, effectively deleting it.

Session Permanency

In certain cases, you may want sessions to stick around even after the user closes their browser. This can be accomplished with Flask’s permanent_session_lifetime variable.

from datetime import timedelta

app = [Flask](https://stackbay.org/modules/learn-flask)(__name__)
app.secret_key = 'TopSecretKey'
app.permanent_session_lifetime = timedelta(minutes=5)

Here we import the timedelta function from the datetime module to set the session lifetime to five minutes.

Security and Sessions

Although sessions in Flask are secure by default, they still contain user data. Therefore, always ensure these sessions are stored over HTTPS, so all data sent between the client and server is encrypted.

There's so much more to learn about managing user sessions and cookies in Flask, but this guide should give you a solid grounding on the topic. With careful management, they can provide a seamless and personalized user experience for your web applications. In our next tutorial, we will look at how we can encrypt user data in Flask to provide additional user privacy and security. Stay tuned!

0 Comment


Sign up or Log in to leave a comment


Recent job openings