The so-called configuration file management means that, without changing the source code, two (or even multiple) configuration files are available for the development environment and production environment respectively, you can use the command line to select a configuration file. some frameworks support multiple configuration files, such as Ruby On Rails and expressjs under nodejs. Although Flask in python supports configuration file management, it is not so convenient to use from_object and from_envvar. Is there a better way?
The answer is the Flask-Environments package. It can automatically select the development environment configuration or production environment configuration through the FLASK_ENV environment variable. Before use, install:
The code is as follows:
$ Sudo pip install Flask-Environments
Modify config. py, write the public configuration and default configuration to the Config class, and write the special configuration for the environment to the classes in each environment:
The code is as follows:
# Config. py
Import OS
Class Config (object ):
DEBUG = True
BASEDIR = OS. path. abspath (OS. path. dirname (_ file __))
HOST = '0. 0.0.0'
PORT = '000000'
Class Development (Config): # inherit from Config
Pass
Class Production (Config ):
DEBUG = False
HOST = '2017. 0.0.1
PORT = 14000
Then, load the configuration where the app object is generated:
The code is as follows:
From flask import Flask
From flask_environments import Environments
App = Flask (_ name __)
Env = Environments (app)
Env. from_object ('config ')
In this way, the development configuration is loaded by default when the application is started in app. run () mode. To start the PRODUCTION environment, you must first set the environment variable FLASK_ENV = PRODUCTION:
The code is as follows:
$ FLASK_ENV = PRODUCTION gunicorn-B 127.0.0.1: 14000 myapp: app