Using randint(0,4) to generate number means that they will sometimes be equal for different users. To generate unique number every time use uuid:

from uuid import uuid4
def random():
    session['number'] = str(uuid4())
    return None

or generator:

import itertools
consequent_integers = itertools.count()

def random():
    session['number'] = consequent_integers.next()
    return None
Answer from Fine on Stack Overflow
🌐
TestDriven.io
testdriven.io › blog › flask-sessions
Sessions in Flask | TestDriven.io
June 4, 2023 - By default, the session object remains in place until the browser is closed. However, if you want to change the life of the session object, define the PERMANENT_SESSION_LIFETIME configuration variable after creating the Flask app:
Discussions

Cannot access session variable set using Flask-Session on a different route on Flask Backend
sessions are powered by cookies. are you calling the logintoapp/landingpage route from another flask app ? or is it being called from the browser? because browsers take care of this cookie <> session business for you. But if you are calling these apis from anywhere other than a browser, then u have to handle the cookies yourself in code. you said this, that is why im doubtful >The codebase that I am currently working on has a Frontend and Backend Server both making use of Flask. More on reddit.com
🌐 r/flask
16
1
October 13, 2022
Beginner question about flask sessions
As I understand it, sessions have to be used in flask whenever you want to work with global variables, You never want to work with global variables. Sessions are sort of the exception to that rule. As you said, they let you store information that is unique per client, and they persist across multiple requests. Does this mean that anything I'd define outside a view function should be a session variable? Can you give an example of when you'd want to do this? would this also apply to a variable I define inside one view function to be used within another view function? This is the primary use for sessions. More on reddit.com
🌐 r/flask
3
1
March 8, 2021
Is there a way to access a Flask Session variable outside of the context of a request?
Not sure if this matches your use case, but the copy_current_request_context decorator from Flask might help with that. Here is an example from the documentation : import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request like you # would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' This example is based on gevent tasks, but you can use the same technique to start a regular thread, as long as you start it at a time when there is an active request context that can be copied, like in this example. More on reddit.com
🌐 r/flask
5
4
June 18, 2018
python - Simple server-side Flask session variable - Stack Overflow
What is the easiest way to have a server-side session variable in Flask? Variable value: A simple string Not visible to the client (browser) Not persisted to a DB -- simply vanishes when the sess... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python Basics
pythonbasics.org › home › flask › session data in python flask
Session data in Python Flask - pythonbasics.org
Session data is stored at the top of the cookie, and the server signs it in encrypted mode.For this encryption, the Flask application requires a defined SECRET_KEY. Practice now: Test your Python skills with interactive challenges · A Session object is also a dictionary object that contains key value pairs for session variables and associated values.
🌐
GitHub
gist.github.com › macloo › 67caf0e0d0718d4723d88786e1db80fb
How Flask session variables work · GitHub
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.
🌐
TutorialsPoint
tutorialspoint.com › flask › flask_sessions.htm
Flask Sessions
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. Session object is also a dictionary object containing key-value pairs of session variables and associated values.
🌐
Reddit
reddit.com › r/flask › cannot access session variable set using flask-session on a different route on flask backend
r/flask on Reddit: Cannot access session variable set using Flask-Session on a different route on Flask Backend
October 13, 2022 -

The codebase that I am currently working on has a Frontend and Backend Server both making use of Flask. Now when the user login's a request is sent from the Frontend to the Backend and a session variable is set. When I use a print statement in this route I am able to see the value of the session variable. Now if the login is valid the user is directed to a landing page, here when I try to print the value of the session variable that was set in the previous route it shows up as None.

Simplified Backend Code

from flask import Flask, session
from flask_session import Session

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)

@app.route('/loginToApp', methods=["POST"])
def loginToApp(): 
    password = request.form.get('password') 
    username = request.form.get('username')

    if verifyLogin(username, password):
        session['username'] = username

    # On print session variable has the expected value
    print(session.get('username'))

    return jsonify({'username': session.get('username')})

@app.route('/landingPage', methods=["POST"])
def landingPage():
    # Value shown as None
    print(session.get('username'))

    return jsonify({'username': session.get('username')})

The /landingPage route can only be accessed using a JWT and on the Frontend I have CORS setup as well. Not sure if these the Flask Extensions that are causing the issues. Requests is used to send the requests from the Frontend to the Backend.

I am unable to figure out what I am doing wrong any and all help would be greatly appreciated.

🌐
DEV Community
dev.to › hackersandslackers › managing-session-data-with-flask-session-redis-360n
Managing Session Data with Flask-Session & Redis - DEV Community
February 12, 2020 - When building we build applications that handle users, a lot of functionality depends on storing session variables for users. Consider a typical checkout cart: it's quite often that an abandoned cart on any e-commerce website will retain its contents long after a user abandons. Carts sometimes even have their contents persist across devices! To build such functionality, we cannot rely on Flask's default method of storing session variables, which happens via locally stored browser cookies.
Find elsewhere
🌐
Hackers and Slackers
hackersandslackers.com › flask-user-sessions-and-redis
Managing Session Data with Flask-Session & Redis
May 27, 2019 - To understand Flask-Session's offering, ... session variables via an in-memory store are essentially limited to either SESSION_MEMCACHED or SESSION_REDIS....
🌐
Reddit
reddit.com › r/flask › beginner question about flask sessions
r/flask on Reddit: Beginner question about flask sessions
March 8, 2021 -

As I understand it, sessions have to be used in flask whenever you want to work with global variables, because normal python global variables could otherwise get shared between servers or between users on the same server. I'm confused as to which variables this applies to?

If you define temporary variables within a view function - such as 'user' etc, basically anything within a def function(): - I know these don't require sessions, so I'm guessing anything defined within a view function and only used within it is fine as a standard non-session-variable. Does this mean that anything I'd define outside a view function should be a session variable? And would this also apply to a variable I define inside one view function to be used within another view function?

🌐
EDUCBA
educba.com › home › software development › software development tutorials › flask tutorial › flask session
Flask Session | How session works in Flask with Examples?
April 11, 2023 - Session in Flask has a concept ... is stored in a server. The object that it is instantiated with that contains the data is a dictionary object that includes key-value pair of session variables ......
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-use-flask-session-in-python-flask
How to use Flask-Session in Python Flask - GeeksforGeeks
March 24, 2025 - The configuration sets the session type (filesystem) and defines whether sessions are permanent. ... from flask import Flask, render_template, redirect, request, session from flask_session import Session app = Flask(__name__) # Configuration app.config["SESSION_PERMANENT"] = False # Sessions expire when the browser is closed app.config["SESSION_TYPE"] = "filesystem" # Store session data in files # Initialize Flask-Session Session(app)
🌐
Reddit
reddit.com › r/flask › is there a way to access a flask session variable outside of the context of a request?
r/flask on Reddit: Is there a way to access a Flask Session variable outside of the context of a request?
June 18, 2018 -

I know session variables can only be accessed once there is a client -> server request but I have a thread that runs concurrently outside of a request. I tried the "with app context" conditional that didn't quite work. Any ideas?

🌐
Medium
medium.com › top-python-libraries › flask-sessions-and-cookies-managing-user-data-across-requests-f313a64ed85f
Flask Sessions and Cookies: Managing User Data Across Requests | by Jayendra | Top Python Libraries | Medium
November 19, 2024 - No signed session data can be created without this key. from flask import Flask, session, redirect, url_for, request, render_template_string app = Flask(__name__) app.secret_key = 'your_secret_key' # Set a secret key to secure the session
🌐
Rip Tutorial
riptutorial.com › accessing and manipulating session variables in your tests using flask-testing
Flask Tutorial => Accessing and manipulating session variables in...
def testSession2(self): with app.test_client() as lTestClient: lResp= lTestClient.post('/getSessionVar') self.assertEqual(lResp.status_code, 200) self.assertEqual(flask.session['sessionVar'], 'hi') Now imagine your function expects a session variable to be set and reacts different on particular values like this
🌐
DataFlair
data-flair.training › blogs › flask-session
How to Use Session in Flask? - DataFlair
July 27, 2023 - The session object can be used to store data that needs to be persisted across requests, such as user authentication status or shopping cart contents. It is a powerful feature of Flask that enables developers to build more sophisticated web applications with a greater degree of interactivity and personalization. Use the statement, for instance, to set the session variable “username.”
🌐
Javatpoint
javatpoint.com › flask-session
Flask Session - Javatpoint
Flask Session with Tutorial, Environment Setup, python, overview, routing, http method, introduction, application, variable rules, url building, request, cookies, static files, file uploading, mail etc.
🌐
Pybites
pybit.es › articles › flask-sessions
Flask Sessions – Pybites
Think of a Flask Session Object as a special variable that persists for the life of the browser session that’s connected to the Flask app.
Top answer
1 of 3
12

I think the Flask-Session extension is what you are looking for.

Flask-Session is an extension for Flask that adds support for Server-side Session to your application.

From the linked website:

from flask import Flask, session
from flask_session import Session  # new style
# from flask.ext.session import Session  # old style

app = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)

@app.route('/set/')
def set():
    session['key'] = 'value'
    return 'ok'

@app.route('/get/')
def get():
    return session.get('key', 'not set')
2 of 3
9

For flask-session 0.3.2, the documentation is here.

There are several available SESSION_TYPESs. filesystem is the most straightforward while you're testing. The expectation is you already have a Redis, database, etc. setup if you are going to use the other SESSION_TYPEs. Section on SESSION_TYPE and requirements

  • null: NullSessionInterface (default)
  • Redis: RedisSessionInterface
  • Memcached: MemcachedSessionInterface
  • filesystem: FileSystemSessionInterface
  • MongoDB: MongoDBSessionInterface
  • SQLAlchemy: SqlAlchemySessionInterface

Code example from the documentation. If you go to /set/ then the session['key'] is populated with the word 'value'. But if you go to /get/ first, then `session['key'] will not exist and it will return 'not set'.

from flask import Flask, session
from flask_session import Session

app = Flask(__name__)

app.config['SESSION_TYPE'] = 'filesystem'
#personal style preference compared to the first answer

Session(app)

@app.route('/set/')
def set():
    session['key'] = 'value'
    return 'ok'

@app.route('/get/')
def get():
    return session.get('key', 'not set')
🌐
TestDriven.io
testdriven.io › tips › 27b1418c-ade2-4a1f-9c57-d8a5e9e4c5a6
Tips and Tricks - How do you "clear" only specific Flask session variables? | TestDriven.io
from flask import session @app.route('/delete_email') def delete_email(): # Clear the email stored in the session object session.pop('email', default=None) return '<h1>Session deleted!</h1>'
🌐
Medium
medium.com › hacking-and-slacking › managing-flask-session-variables-f4c5ccef54c0
Managing Flask Session Variables
February 11, 2020 - Using Flask-Session and Flask-Redis to store user session variables.