0

How can I use a value created by an outside program before starting of the flask run?

If it is not possible then how can a variable which gets assigned in __init__.pyat the start of flask app be used inside files which are registered through blueprint.register?

Ex:

__init__.py

   var1 = "SOMETHING"

routes.py

  if var1 = "SOMETHING":
     call api1 
  else
     call api2

Basically the question is: How to share variables between __init__.py and those *.py files which are connected through blueprint.

furas
  • 134,197
  • 12
  • 106
  • 148
Gsb
  • 3
  • 3
  • I never tested but how about using `app.config["var1"] = "SOMETHING"` ? Or maybe when you use `Blueprint()` then add these values as arguments ? – furas Jun 17 '20 at 18:21
  • Thanks. I tried this way. But it gives error " app" not found. Please remember that I am trying to use this config value inside dl_routes.py which is added using blueprint.register() method. How to make `app` accessible inside `dl_routes.py` ? – Gsb Jun 18 '20 at 13:12
  • @Gsb Inside a blueprint, you use current_app, not app. – BaSsGaz Feb 22 '23 at 17:23

1 Answers1

0

The common practice is to use environmental variables for such purposes. On unix systems you can easily set variable by another utility using:

export VARIABLE="SOMETHING"

Then you can access such variable in your code in following way:

os.getenv("VARIABLE", "some default value")

Consequently, your example would look like below:

import os

var1 = os.getenv("VARIABLE", "SOMETHING ELSE")
if var1 = "SOMETHING":
   call api1 
else
   call api2

You can find more details how to use environmental variables with flask in its documentation: https://flask.palletsprojects.com/en/1.1.x/config/


The advantage of using environmental variables is ease of providing configuration for your application in containerized environments e.g. in kubernetes or docker.

  • Thanks for the reply. I am now using `os.environ['VAR1'] = 'SOMETHING' ` inside main `__init__.py` and in my `dl_routes.py` took the value back by using `current_var = os.getenv('VAR1') ` . The problem is each time the function inside `dl_routes.py` is called, `os.getenv()` function is executed. But is there any way to avoid calling this `os.getenv()` each time? Is there a way to set a variable inside main `__init__.py` and later use it inside `dl_routes.py` as a variable like a **one-time** variable assignment? – Gsb Jun 18 '20 at 02:11