I'm creating a game on Flask and want to have a counter across the entire session. I put together some psuedo code for the general outline of the project. Basically it's a script that pulls a random question from a database, collects user input, returns the correct answer, and then starts over again at the user input route. I want to add a counter that will appears regardless of the function of route. I looked into Flask sessions, but it was confusing where or how to implement... any thoughts/ suggestions? Sessions or otherwise?
get_db_info():
connects to a database
@app.route('/questions')
def user_input():
collects user input and puts into variable
@app.route('/answers')
def results():
if user input = results:
print(correct!)
elif:
print(incorrect)
renders back to user_input()
You already mention sessions, I think they are the solution to your problem:
Here is an example of doing this with a session. It stores three counters, one for total accesses to the app and two for accesses to individual routes. If you call
/A
three times and then/B
, it will give youThe session behaves like a dictionary and is available across all routes. You can simply put your counter there.
For the sake of completeness, a solution without sessions is also possible: In principle, the flask routes behave just like python functions. So the following will work:
I would discourage the use of globals, they can make your code very hard to read and are not thread safe.