How to use multiple configuration files in the python WEB framework Flask

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.