Flask session simplest example

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)



Related Posts

Expiring Links Tutorial: Python Flask One-Time Link Generator
June 15, 2024

One time links are essential where users want to share resources with co-worker or friend’s effortlessly but at the same time restrict other from access. Its works best because the link automatically inactive if some one go to the link for the first time. That means the same link will not work for the second […]

Create your first chat application with Flask and Socketio
April 27, 2024

We will use socketio for real-time messaging First install our dependency for this application pip install flask pip install flask-socketio Copy Code How it will work. Every user will get an unique key. If the the other user submit the other users key that will send the message. its like sending message to unique username […]

Ajax example with flask
April 27, 2024

One of the best ajax applied in real world is username checker. In this example we will check if there is existing username This is code /project we will Our first step: Check if username exists or not Imagine we have this existing username when the user enter a username we will check it from […]