Mote Zart
Mote Zart

Reputation: 960

Access\Read Flask Env Variable within app

I can't seem to access my env variables' values inside my app. I'm loading my env variables into my app with a .env file and the dotenv package; I learned about it here.

My .env

FLASK_ENV=development
FLASK_APP=app.py
DEBUG=ON
TESTING=False

I want to use the value of the TESTING variable inside my app and run certain code based on whether it is True or False.

How can I get these values? The docs say

Certain configuration values are also forwarded to the Flask object so you can read and write them from there: app.testing = True

But I get module 'app' has no attribute 'testing'

When I log app by itself I see a Flask object. When I log this out like app.Flask, I see the env variables, but these appear like this, with no refernce to the current value.

{'__name__': 'TESTING', 'get_converter': None}

I want to be able to do something like:

app.testing => False
app.FLASK_ENV => development

and then eventually:

if app.testing == True:
    <do something>

PS - I know the app loads this .env file okay because if I remove the values the environment changes back to production, the default.

#settings.py
from pathlib import Path  # python3 only
from dotenv import load_dotenv
load_dotenv(verbose=True)
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

Upvotes: 1

Views: 1937

Answers (1)

Mote Zart
Mote Zart

Reputation: 960

import os
print(os.environ['TESTING'])

Equivalent in JS is process.env

Upvotes: 2

Related Questions