Using a shared variable between routes and main in flask

544 Views Asked by At

I have a python flask server. In the main of my script, I get a variable from user that defines the mode of my server. I want to set this variable in main (just write) and use it (just read) in my controllers. I am currently using os.environ, but I 'm searching for more flasky way to use.

I googled and tried following options:

  1. flask.g: it is being reset for each request; so, I can't use it inside controllers when it is being set somewhere else.
  2. flask.session: it is not accessible outside request context and I can't set it in the main.
  3. Flask-Session: like the second item, I can't set it in the main.
1

There are 1 best solutions below

0
furas On BEST ANSWER

In main you use app.run() so app is avaliable in main. It should be also avaliable all time in all functions so you can try to use

app.variable = value

but flask has also

app.config

to keep any settings. See doc: Configuration Handling