Alex T
Alex T

Reputation: 3754

Running flask app with gunicorn and environment variables

For local development I simply set .env file that contain necessarily variables and just run the app with:

Flask run

Everything seems fine, all the environment variables are being read and set correctly in the app.

However when I run the app with gunicorn:

gunicorn api:app --bind 127.0.0.1:5050

I can see clearly that env variables are not loaded.

Only If I set them explicitly in gunicorn command:

gunicorn api:app --bind 127.0.0.1:5057 -e POSTGRES_DB=postgresql://XXXXX

then it will work. However since I can have many environment variables this is not really feasible. Is there a way to set this using file?

Upvotes: 7

Views: 4187

Answers (1)

dmitrybelyakov
dmitrybelyakov

Reputation: 3864

Gunicorn can read gunicorn.conf.py file which is just a normal python file where you can set your environment variables:

# gunicorn.conf.py
import os
os.environ['POSTGRES_DB'] = "postgresql://XXXXX"

You can even tell it to load your .env files with something like:

# gunicorn.conf.py
import os
from dotenv import load_dotenv

for env_file in ('.env', '.flaskenv'):
    env = os.path.join(os.getcwd(), env_file)
    if os.path.exists(env):
        load_dotenv(env)

Upvotes: 16

Related Questions