Workarounds for using multiple configuration files in Python's web framework Flask

Source: Internet
Author: User
Tags ruby on rails
Some frameworks natively support multiple configuration files, such as Expressjs under Ruby on Rails,nodejs. Although flask under Python natively supports profile management, it is not so convenient to use From_object and From_envvar alone. Is there a better way?

The answer is flask-environments this bag. It can automatically select the development environment configuration or production environment configuration through the FLASK_ENV environment variable. Before you use it, install it first:
Copy the Code code as follows:

$ sudo pip install flask-environments


Then modify the config.py, write the common configuration and default configuration to the Config class, and write the classes for each environment for the special configuration of the environment:
Copy CodeThe 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 = ' 8000 '

Class Development (config): # Inherit from Config
Pass

Class Production (Config):
DEBUG = False
HOST = ' 127.0.0.1
PORT = 14000


Then load the configuration where the App object is generated:
Copy CodeThe code is as follows:


From flask import Flask
From flask_environments Import environments

App = Flask (__name__)
env = environments (APP)
Env.from_object (' config ')


This way, the development configuration is loaded by default when it is started by App.run (). To start a production environment, set the environment variable flask_env=production first:
Copy CodeThe code is as follows:


$ flask_env=production gunicorn-b 127.0.0.1:14000 Myapp:app
  • Related Article

    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.