Forums

[FLASK] How to have a persistent variable across requests ?

Hello,

In my script I have different global variables that I want to be global for all requests users make. For example I initialize a global variable :

EMOTE_LIST = [0]

And then I modify it in a function

def function1():
    global EMOTE_LIST
    EMOTE_LIST.append(10)

I want this EMOTE_LIST variable to keep these changes, across all users new HTTP requests that my Flask application handles.

Currently, it seems like on each request, EMOTE_LIST value is always EMOTE_LIST = [0]

The reason for all this, is because I have a database on another server that holds emote information. This database is updated every 30 minutes or so. For each request I need this emote list, so in my Flask application I make a SQL Query to my distant database to retrieve it.

However it takes about 20 seconds to complete, so when users use this specific endpoint, it always take 20+ seconds to complete.

This emote list loaded in my Flask application, I don't need to update it at each request. I want to load it once, and then update it every 30 minutes. So I need a global variable to do that. I set everything up, with the timer to check when to update it and all. But I just noticed that the variable isn't persistent across new requests.

Surely there's a way to do it ?

Thank you for your help !

See out help page about global state in web apps: https://help.pythonanywhere.com/pages/GlobalStateAndWebApps/