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 OverflowUsing 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
So you do something like this. It is not tested but should work. You retrieve the current username and the numbers dictionary from the session variable. Check if there is an existing value for the current username. If not create a random number and save it in the session. Else just use the saved value.
@app.route('/check', methods=['GET', 'POST'])
def check():
# retrieve current username and numbers from your session
username = session['username']
numbers = session.get('numbers', {})
# if no number is existing create a new one and save it to session
if username not in numbers:
number = randint(0,4)
numbers['username'] = number
session['numbers'] = numbers
else:
number = numbers['username']
return render_template('file.html', number=number, user=username)
Cannot access session variable set using Flask-Session on a different route on Flask Backend
Beginner question about flask sessions
Is there a way to access a Flask Session variable outside of the context of a request?
python - Simple server-side Flask session variable - Stack Overflow
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.
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?
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?
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')
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')