Potential 'global' variable workaround?

In the documentation it is described that one should not use global variables. I thought of a potential workaround (to keep global variables) and I wanted to know your thoughts. I’m currently implementing it into my project, and will keep the community posted with results:
In the global space:

session_variables = {
}
...

Within the app layout, include the following element: dcc.Location(id=‘url’, refresh=False),
Assume that the app is being run in a directory: /user1/documents/app_dir
Then the url should also include the path to the file containing whatever data the app will read from:

http://localhost:8050/user1/documents/app_dir/data.csv for user1

Another user wants to use the app (and has access to user1’s directory, and visits the following url:

http://localhost:8050/user1/documents/app_dir/another_dataset.csv for user2

Then in an app callback:

@app.callback(Output('something','children'),
                 [Input('url','pathname')]
    )
    def change_display_message(pathname):
        global session_variables
        if os.path.isfile(pathname):
            session_variables[pathname] = pd.read_csv(pathname)
        return something

In all other callbacks that require a specific dataset, one of the Inputs would have to be the url (which is stored in the user’s current session).

Like I mentioned, I will definitely update the community with my findings, but I want to open this for discussion to see what other people think, or have tried something similar and what are their findings.

Cheers!

Using global variables like this might work when you are running a single app instance, but when you scale up your application with more workers, each worker will have its own memory and the session data will get out of sync from worker to worker (as a request can happen on any of the workers, even within a session).
By multiple workers, i mean when you run dash with gunicorn or waitress.
This is why we recommend the solutions outlined in the tutorial: save the data in the front end with Store or use a shared memory store like Redis.
https://dash.plot.ly/sharing-data-between-callbacks

2 Likes

Hmmm interesting, I wasn’t aware that:

a request can happen on any of the workers, even within a session

I did read over that hyperlink before, but that helped clear it up for me. I appreciate your response @chriddyp !

1 Like