0

In __init__.py, I set the environment variable.

import os

# set mkey environment variable
MKEY="xxxx"
os.environ["MKEY"] = MKEY

And then I try to read the environment variable in another file - file1.py

import os
token = os.environ["MKEY"]

When I attempt to run the app on localhost, I get an error:

Traceback:

token = os.environ["MKEY"]
  File "/Applications/Anaconda/anaconda3/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'MKEY'

It looks like the environment variables are not being set properly or are only accessible in the file they are being set. I don't see them here either:

for key in os.environ.keys():
    print(key + ": " + os.environ[key])

How do I set environment variables that can be accessed across all files in my Flask App? Is there a way to set this in one of the files versus using export in the root directory?

kms
  • 1,810
  • 1
  • 41
  • 92
  • `os.environ` sets the variable for the current session only. Use export for Linux or do it via registry for Windows. – Cow Dec 05 '22 at 06:53
  • @user56700 - Is there a way to set this in one of the files? – kms Dec 05 '22 at 06:56
  • https://stackoverflow.com/questions/716011/why-cant-environmental-variables-set-in-python-persist – Cow Dec 05 '22 at 06:57
  • you can use singleton object ie dictionary to store the env variables and use the data from there and can use decorator if there is any update then export the data to env file something like that – sahasrara62 Dec 05 '22 at 07:41
  • @sahasrara62 mind writing up an answer? i'm not sure if I follow your comment. – kms Dec 05 '22 at 07:46
  • I think it's probably less related to *"being in the same file"* and more related to *"being in the same process"*. Environment variables can not be seen across different processes and WSGI and Nginx are both allowed to use multiple processes (and threads) to improve performance. – Mark Setchell Dec 05 '22 at 08:17

1 Answers1

1

maybe write a config file, say config.py where load all env in object like

config = {'db': os.getenv('user', 'user_db')}

and

set env there like , you are doing

os.environ['mike'] = mike

then do

config['mike'] = os.environ['mike']

and use this config object in the other file like

from config import config

you can write a function to set and update the configs

something like this you can do

sahasrara62
  • 10,069
  • 3
  • 29
  • 44