Configuration in Python flask

Source: Internet
Author: User
Tags rounds using git version control system

When you start learning flask, the configuration looks like a piece of cake. You just need to define a few variables in config.py and then everything. However, when you have to manage the configuration of a production application, all this will become tricky. You have to try to protect the API keys, or to use different configurations for different environments, such as the development and production environments. In this chapter we will explore some of the advanced features of flask, which make configuration management easier.

Start Small

A simple application does not require any complex configuration. You just need to place a config.py file in your root directory and load it in app.py or yourapp/__init__.py .

Each line in the config.py should be an assignment statement for a variable. Once the config.py is loaded later, this configuration variable can be app.config obtained through a dictionary, for example app.config["DEBUG"] . The following is an example of a config.py file for a small project:

True # 启动Flask的Debug模式BCRYPT_LEVEL = 13 # 配置Flask-Bcrypt拓展MAIL_FROM_EMAIL = "[email protected]" # 设置邮件来源

Some configuration variables are built-in, such as DEBUG . There are also configuration variables that are related to flask expansion, for example, BCPYRT_LEVEL for Flask-bcrypt expansion (an extension of the hash map password). You can even define your own configuration variables used in this application. In this example, I use the app.config["MAIL_FROM_EMAIL"] default sender to indicate when a message is being exchanged (such as resetting a password). This makes it difficult to change in the future without too much trouble.

In order to load these configuration variables, I usually use the app.config.from_object() . If it is a single module application, it is in app.py, or in yourapp/__init__.py, if it is a package-based application. In either case, the code looks like this:

from flask import Flaskapp = Flask(__name__)app.config.from_object(‘config‘)# 现在通过app.config["VAR_NAME"],我们可以访问到对应的变量
Some important configuration variables
variables Description Default Value
DEBUG Give you some useful tools when debugging errors. For example, when a request causes an exception to occur, a call stack and a Python command line will appear for the Web interface. Should be set to true in the development environment and should be set to false in the production environment.
Secret_key Flask uses this key to sign cookies and other things. You should set this value in the instance folder and do not put it in version control. You can read more information about the instance folder in the next section. This should be a complex arbitrary value.
Bcrypt_level If you use Flask-bcrypt to hash the user's password (if not, use it now), you need to specify the value of "rounds" for the hash password algorithm. The higher the rounds value is set, the longer it takes to calculate the hash (the same effect is on the cracked side, and this is important). The value of rounds should increase as your device's computing power increases. If you use Flask-bcrypt to hash the user's password (if not, use it now), you need to specify the value of "rounds" for the hash password algorithm. The higher the rounds value is set, the longer it takes to calculate the hash (the same effect is on the cracked side, and this is important). The value of rounds should increase as your device's computing power increases.

Ensure that the production environment is set up DEBUG = False . If you forget to turn it off, users will be happy to execute arbitrary python code on your server.

Instance folder

Sometimes you need to define some configuration variables that are not known. To do this, you'll want to isolate them from other variables in the config.py and keep them out of version control. You might want to hide secrets like database passwords and API keys, or define parameters specific to the current machine. To make this easier, flask provides a feature called the instance folder . The instance folder is a subfolder of the root directory that includes a configuration file that is specific to the current application instance. We do not submit it to version control.

This is the structure of a simple flask application that uses the instance folder:

config.pyrequirements.txtrun.pyinstance/  config.pyyourapp/  __init__.py  models.py  views.py  templates/  static/
Using the Instance folder

To load the configuration variables defined in the instance folder, you can use the app.config.from_pyfile() . If you set the call Flask() when you create an app instance_relative_config=True , you app.config.from_pyfile() will see a special file in the instance folder.

app = Flask(__name__, instance_relative_config=True)app.config.from_object(‘config‘)app.config.from_pyfile(‘config.py‘)

Now you can define variables in instance/config.py , as in config.py. You should also add the instance folder to the Ignore list of the version control system. For example, if you are using Git, you need to open a new line in Gitignore and write it down instance/ .

Secret key

The hidden properties of the instance folder make it a good place to hide keys. You can put in the app's key or the third party's API key. If your application is open source, or it will be open source, it will be important. We want other people to use the keys they have applied for themselves.

# instance/config.pySECRET_KEY = ‘Sm9obiBTY2hyb20ga2lja3MgYXNz‘STRIPE_API_KEY = ‘SmFjb2IgS2FwbGFuLU1vc3MgaXMgYSBoZXJv‘SQLALCHEMY_DATABASE_URI= "postgresql://user:[email protected]/databasename"
Minimizing the environment-dependent configuration

If the difference between your production environment and your development environment is very small, you can use your instance folder to erase the differences on the configuration. The variables defined in instance/config.py can override the values set in the config.py . You just have to app.config.from_object() call it later app.config.from_pyfile() . One of the advantages of doing this is that you can modify the configuration of your app on different machines. Your development repository might look like this:

config.py

DEBUG = FalseSQLALCHEMY_ECHO = False

instance/config.py

DEBUG = TrueSQLALCHEMY_ECHO = True

Then, in a production environment, you remove the code from instance/config.py , and it will instead use the variable set in config.py .

See

  • Here you can read the configuration key about Flask-sqlalchemy: Http://pythonhosted.org/Flask-SQLAlchemy/config.html#configuration-keys
Configure according to environment variables

The instance folder should not be in version control. This means that you will not be able to track your instance configuration. This is not a problem in cases where there are only one or two variables, but if you have a lot of configuration about multiple environments (production, stability, development, etc.), you will not be willing to risk losing them.

Flask gives us the ability to select a profile based on the environment variable. This means that we can have multiple profiles in our repository and always be able to load to the right one depending on the environment.

When we get to a situation where multiple profiles coexist, it's time to move the files config under the package. Here's what it looks like in a repository like this:

requirements.txtrun.pyconfig/  __init__.py # 空的,只是用来告诉Python它是一个包。  default.py  production.py  development.py  staging.pyinstance/  config.pyyourapp/  __init__.py  models.py  views.py  static/  templates/

In the case where we have a few different configuration files, we can set this up:

file name content
config/default.py The default value, which applies to all environments or to specific environments for overwriting. For example, set in config/default.py DEBUG = False , set in config/development.py DEBUG = True .
config/development.py The value to use in the development environment. Here you can set the database URI link used in localhost.
config/production.py The value to use in the production environment. Here you can set the URI link for the database server, not the local database URI link under the development environment.
config/staging.py In your development process, you may need to test your app on a server that simulates a production environment. You might use a different database and want to replace some configuration for a stable version of your app.

To specify the required variables in a different environment, you can call app.config.from_envvar() :

# yourapp/__init__.pyapp = Flask(__name__, instance_relative_config=True)app.config.from_object(‘config.default‘)app.config.from_pyfile(‘config.py‘) # 从instance文件夹中加载配置app.config.from_envvar(‘APP_CONFIG_FILE‘)

app.config.from_envvar(‘APP_CONFIG_FILE’)The file specified by the environment variable is loaded APP_CONFIG_FILE . The value of this environment variable should be the absolute path to a configuration file.

How this environment variable is set depends on the platform you are running your app on. If you are running on a standard Linux server, you can use a shell script to set up environment variables and run them run.py .

start.sh

APP_CONFIG_FILE=/var/www/yourapp/config/production.pypython run.py

start.sh is specific to an environment, so it cannot be put into version control. If you host the app to Heroku, you can set the environment variable parameters with the tools provided by Heroku. The same process is true for other PAAs platforms.

Summarize
    • A simple application may require only one profile:config.py
    • The instance folder helps us to hide configuration variables that we don't want to know about.
    • The instance folder can be used to change the configuration of a program in a particular environment.
    • Dealing with complex, environment-based configurations, we can combine environment variables and app.config.from_envvar() use them.

Configuration in Python flask

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.