Home > Software engineering >  How to use `FLASK_ENV` inside configuration objects?
How to use `FLASK_ENV` inside configuration objects?

Time:04-13

Following the examples for Development / Production from Flask documentation. Is not possible to use FLASK_ENV to configure flask environment?

>>> class DevelopmentConfig(Config):
...     FLASK_ENV = "development"
...     DEBUG = True
... 
>>> class ProductionConfig(Config):
...     FLASK_ENV = "production"
...     DEBUG = False
... 
>>> def create_app(config="ProductionConfig"):
...     app = Flask(__name__)
...     app.config.from_object(f"{__name__}.{config}")
...     return app
... 
>>> app = create_app("DevelopmentConfig")  # I CREATE AN APP USING DevelopmentConfig
>>> app.run()
 * Serving Flask app '__main__' (lazy loading)
 * Environment: production  # WHY IS ENVIRONMENT SET TO PRODUCTION?
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL C to quit)

CodePudding user response:

Although you can set ENV and DEBUG from the settings it may not work as expected and is not recommended.

In order to set the environment and debug mode reliably, Flask uses environment variables.

For your reference, Environment and Debug Features

CodePudding user response:

So I finded out, although externally you should use FLASK_ENV internally you should just use ENV.

>>> class DevelopmentConfig(Config):
...     ENV = "development"  # USE ENV INSTEAD OF FLASK_ENV
...     DEBUG = True
... 
>>> class ProductionConfig(Config):
...     ENV = "production"  # USE ENV INSTEAD OF FLASK_ENV
...     DEBUG = False
... 
>>> def create_app(config=ProductionConfig):
...     app = Flask(__name__)
...     app.config.from_object(config)
...     return app
... 
>>> app = create_app(DevelopmentConfig)
>>> app.run()
 * Serving Flask app '__main__' (lazy loading)
 * Environment: development  # NOW IS SET CORRECLY
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL C to quit)
  • Related