A session with each client is assigned a Session ID. The Session data is stored on top of cookies and the server signs them cryptographically. For this encryption, a Flask application needs a defined SECRET_KEY.
The following code is a simple demonstration of session works in Flask.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = 'cairocoders-ednalan0711' @app .route( '/' ) def index(): if 'username' in session: username = session[ 'username' ] return 'Logged in as ' + username + '<br>' + \ "<b><a href = '/logout'>click here to log out</a></b>" return "You are not logged in <br><a href = '/login'></b>" + \ "click here to log in</b></a>" @app .route( '/login' , methods = [ 'GET' , 'POST' ]) def login(): if request.method = = 'POST' : session[ 'username' ] = request.form[ 'username' ] return redirect(url_for( 'index' )) return "<form action = '' method = 'post'> " + \ "<p><input type = text name = username></p> " + \ "<p><input type = submit value = Login></p> " + \ "</form>" @app .route( '/logout' ) def logout(): # remove the username from the session if it is there session.pop( 'username' , None ) return redirect(url_for( 'index' )) if __name__ = = '__main__' : app.run(debug = True ) |