Flask sessions are useful when we want to remember a specific user. For example to know the user already visited the website before. So we can generate dynamic content for that user. Or we can use login based system
In this code we will use the simplest flask session example
Run the code go the page.It will show the welcome paragraph. Then reload the page. When reload the page. it will show the user their unique id. .
So we can generate the dynamic content for that specific user.
from flask import Flask, session, request, render_template
import random
app = Flask(__name__)
# Its just for the example. Always store secret key in environment variable
app.secret_key = '938275934875934875934812345'
@app.route('/')
def index():
if 'user_id' in session:
user_id = session['user_id']
return f'Welcome back, User {user_id}!'
else:
session['user_id'] = generate_user_id()
return 'Welcome, new user!'
def generate_user_id():
return random.randint(1, 1000000)
if __name__ == '__main__':
app.run(debug=True)