How to set FLASK_ENV inside config file?

Update march 2020:

According to the Flask devs, you cannot do this anymore:

The ENV and DEBUG config values are special because they may behave inconsistently if changed after the app has begun setting up. In order to set the environment and debug mode reliably, Flask uses environment variables.

The environment is used to indicate to Flask, extensions, and other programs, like Sentry, what context Flask is running in. It is controlled with the FLASK_ENV environment variable and defaults to production.

Setting FLASK_ENV to development will enable debug mode. flask run will use the interactive debugger and reloader by default in debug mode. To control this separately from the environment, use the FLASK_DEBUG flag.

To switch Flask to the development environment and enable debug mode, set FLASK_ENV:

> $ export FLASK_ENV=development 
> $ flask run (On Windows, use set instead of export.)

Using the environment variables as described above is recommended. While it is possible to set ENV and DEBUG in your config or code, this is strongly discouraged. They can’t be read early by the flask command, and some systems or extensions may have already configured themselves based on a previous value.


What about this: install python-dotenv package, create a .flaskenv file in your project root folder and add, for example, this:

FLASK_APP=app.py (or whatever you named it)
FLASK_ENV=development (or production)

Save. Do flask run.


If you move your config into Python, things get a little easier. Consider

from flask import Flask
from config import Config

app = Flask(__name__)
app.config.from_object(Config)

where config.py looks like

import os

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY', 'default sekret')

This gives you defaults that can be overridden from environment variables.


Though it may not be recommended, you can create a custom script and set it there.

manage.py

#!/usr/bin/env python

from os import path as environ

import click

from flask import Flask
from flask.cli import FlaskGroup

def create_app():
    app = Flask(__name__)
    ...
    return app


@click.group(cls=FlaskGroup, create_app=create_app)
@click.option('-e', '--env', default="development")
def manager(env):
    environ["FLASK_ENV"] = env


if __name__ == "__main__":
    manager()

Now in the command line (after running pip install manage.py) you can do manage run or manage -e production run.

Used in combination with the app factory pattern, you can dynamically change the configuration as well.

Tags:

Python

Flask