I use python Flask for a web application. I can not deal with the sessions. I saw lots of examples, but there is no clear picture in my head. Here for example what code is written to create sessions.

def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' @app.route('/logout') def logout(): # remove the username from the session if it is there session.pop('username', None) return redirect(url_for('index')) 

The question is as follows. But for one user, everything is clear, but when there are a large enough number, where do I get this 'username' to terminate the session for the user who pressed the logout on the site?

    1 answer 1

    Each user has his own session in which data relating only to him is stored.

    If to simplify strongly enough, the session can be imagined as a dictionary, where the key will be a certain user ID that the browser sends us, and the value will be the session data:

     { 'aa04c3e7-c9f8-4d6f-b859-0162cf5b5af4': { 'id': 20, 'last_login': 1478351885 'username': 'Aleksey' }, '5253b4fe-cf1d-4b76-8d73-e125457d8cf7': { 'id': 21, 'last_login': 1478323910 'username': 'Ivan' }, 'f1e7f9a8-858c-4613-994d-340022420d62': { 'id': 22, 'last_login': 1478351918 } } 
    1. The user clicks the link /logout .
    2. Flask receives the user's session ID from the browser and passes it to the session manager. For example: 5253b4fe-cf1d-4b76-8d73-e125457d8cf7 .
    3. The session manager, based on the received identifier, identifies the logged in user as id = 21 and substitutes the session data into the session object, which will be available in the logout() function / view:

    session = { 'id': 21, 'last_login': 1478323910, 'username': 'Ivan' }

    • I more or less understand this, I do not understand what is required directly in the code. - dyop
    • @dyop, 'username' not needed from anywhere, this is the text key of the session object: session => {'username': 'Ivan'} ; session.pop('username', None) ; session => {} ; Everything is already quite logical in your code, the .pop command deletes the .pop from the session if it is there. - anatolii
    • Is the session will not be replaced? The first one came, say 'Ivan' , went through the login , another 'Alex' comes in, and if you do print(session) , the value changes. - dyop
    • @dyop, no, the value is not replaced. For each user, their values, they are simply replaced depending on the user, but do not go anywhere. - anatolii