Sign out of Flask

We have already seen how sessions are managed in Flask. Today we are going to see how we should log out of Flask.

Create the session

The first thing we will do is upload data to the session using the session object
Flask and the variable name that we want to store.

session["name"] = name
session["last name"] = last name

From this moment on these two variables will be available in all requests made by the user since they travel in the cookie that is managed with the user.

Log out of Flask

We have two ways to log out of Flask. The first is to delete field by field all the information that we have saved. This can be simple if the number of fields we have managed is small. The second thing we can do is directly delete the entire session. But let’s see how each of them works.

Delete Session Fields

To be able to delete fields from the session in Flask we use the .pop() method. This method receives as a parameter the name of the field we want to eliminate and a value of None.

session.pop('name',None)
session.pop('last name',None)

Delete entire session

In the event that we want to delete all the session information we must use the .clear() method directly on the session object.

session.clear()

In this way all the fields that we have uploaded to the session and the cookie that is exchanged with the user’s browser will be deleted.

Now you only have to see which of the two ways to log out of Flask is more interesting for your application.