Flask Restful App not loading environment variables using waitress

341 Views Asked by At

I have a Flask REST app, which used to run via gunicorn on an ubuntu server, now have to move the deplpoyment to windows hence using waitress for deployment but its not able to load the env variables:

Project Structure is like:

  1. app.py
  2. setup.py
  3. config.py
  4. .env

.env:

VARIABLE_1=SECRET_1
DB_URL=URL_STRING

config.py

import os;
config = {
   "variable_1": os.getenv("VARIABLE_1")
   "db_url": os.getenv("DB_URL")
}

setup.py contains all the initaialization logic:

// Other Imports

from config import config

def create_app():

    app = FLASK(__name__)
    /* more initialization like CORS, jwt etc  */

    app.config['MONGODB_SETTINGS'] = {
      "host": config['db_url'] // waitress not able to fetch env variables, gunicorn and flask were able to
    }

    /* other stuff */

    return app;

app.py is the starting point of app:

from setup import create_app
from dotenv import load_dotenv
import os
from waitress import serve

if __name == "__main__":
   app = create_app()
   app.run()
else:
   for env_file in ('.env', '.flaskenv'):
     env = os.path.join(os.getcwd(), env_file)
     if os.path.exists(env):
       load_dotenv(env) // here doing os.getenv('env_name') shows value properly but in setup.py they are not loading 
   serve(app, host="some_host")

Running application through waitress-serve using waitress-serve app:create_app

env variables are not loading through config.py file using waitress with flask run and gunicorn the app runs properly

What do I need to add/fix to make my application work ?

1

There are 1 best solutions below

0
diegolikescode On

I see you are using waitress and dotenv, but to get the env variable you use os.getenv, which is fine when running your app with app.run(...), but with waitress you can use dotenv.get_key('.env', 'MY_ENV_VAR'):

if __name__ == '__main__':
    load_dotenv()

    if os.getenv('PY_ENV') == 'PROD':
        serve(app, listen=f'{os.getenv("HOST")}:{os.getenv("PORT")}')
    else:
        app.run(host=os.getenv('HOST'), port=os.getenv('PORT'), debug=True)

this is working, but as I said, with waitress you will not be able to use os.getenv(), so you do:

dotenv.get_key('.env', 'MY_ENV_VAR')

and assuming that you have a .env or something like this in the root of your project, it'll work. I hope it helps.

just so you know, I'm using python 3.10, waitress=2.1.2, python-dotenv=0.20.0 and Flask=2.0.3