The use of the session in any web system is used to store information related to a user, in which data such as the name, identifier, that is, of an authenticated user is stored, as we will see in the next section; at the moment, we do not have a use for it so we will continue using the session in later chapters and we will see some examples of its use.
Another common example of using the session is shopping carts, to record each of the products to be purchased.
The data stored in the session is temporary data, since the session will eventually expire.
The session is usually modified, understood as adding, updating and deleting references as requests are made to the server, for example, when a user is going to authenticate after a successful login, the data of the authenticated user is recorded in the session, when will close the session, this data is destroyed, if you have a shopping cart, when making the purchase, all this data is deleted from the session.
To use the session, a secret key must be established, which is established from the beginning of the project in the configuration file:
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
First tests with the session
To use the session, we must import the object called session that is part of the framework:
from flask import session
With this, we can set data like in the session as if it were an array:
session['username'] = 'user'
And obtain this data using:
session['username']
Or remove the data:
session.pop('username', None)
You can see a complete example, implementing the following drivers in some test file:
from flask import session
***
@app.route('/test/session/check')
def test_session_check():
if 'username' in session:
return 'Logged in as '+session["username"]
return 'You are not logged in'
@app.route('/test/session/set')
def test_session_set():
session['username'] = 'user'
return 'Test'
@app.route('/test/session/pop')
def test_session_pop():
session.pop('username', None)
return 'Test'
Y evaluar el resultado.
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter