Python-decouple Introduction

Source: Internet
Author: User

Change Article main translation: https://pypi.python.org/pypi/python-decouple/

There is no place to look at the great God point out, thank you.

decouple Introduction :

Detach the settings from the code
Decouple will help you to parse your program configuration file to achieve the effect of changing your settings without redeploying the program


decouple will be very handy to help you do the following things:
1. Store your parameters in the INI or. env file 2. Define your default values 3. Properly convert your configuration to the appropriate value 4. Only one configuration module is required in your program to set up   Decouple was first developed for Django, and later became a standalone, generic tool that separates the configuration from the code   Why use decouple?

Typically, the web framework sets different kinds of parameters:

1. Language environment and internationalization 2. Middleware and Applications 3. Resource Storage Related: Database, Cache class. Wait 4. External service voucher: Amazon S3 or Twitter 5. Setting up the pre-launch environmentThe first two are the settings for the entire project, followed by the settings for the deployment instance     Why don't we use environment variables directly? environment variables are obtained by Os.environ, but strings are returned, which is tricky For example, you have a Environment Change Debug=false, you may be able to run the following code This code will return Tru e, because os.environ[' DEBUG ' returns a The string "False", because this is a non-empty string, so returns True Decouple provides a solution that solves this problem : Config (' DEBUG ', Cast=bool)  
if os.environ['DEBUG':    print  TrueElse  :    Print False

Installation of decouple:

Pip Install Python-decouple

How to use: in the in your settings.py file, you can write this: 1. import the Config object:
 from Import Config


2. Get Configuration parameters
Secret_key = Config ('secret_key'= config ('DEBUG'), Default=false, cast== config ('email_host', default='  localhost'= config ('email_port', default=25, cast= int

Where should these configuration files be placed? Decouple supports two types:. ini files and. env Files INI File example: Create a Settings.ini file, the next step in your file can be written in the following format configuration, for example:
[Settings]debug=truetemplate_debug=%(DEBUG) Ssecret_key=arandomsecretkeydatabase _url=mysql://myuser:[email protected]/mydatabasepercentile=90%%#commented=42

Note: Because the Configparser module supports the reason for string padding, percent percent should be replaced by the climbed semicolon, which is env File Example:

Create an. env file in the root directory of your program, for example:

Debug=truetemplate_debug=truesecret_key=arandomsecretkeydatabase_url=mysql://myuser:[email protected]/ mydatabasepercentile=90% #COMMENTED =42
How do I use it in Django? if I have an. env file in the root of my program, here is a fragment of my setting.py program, the following program, which I recommend for use with Unipath and Dj-database-url:
#Coding:utf-8 fromDecoupleImportConfig fromUnipathImportPath fromDj_database_urlImportParse as Db_url base_dir= Path (__file__). Parent DEBUG= Config ('DEBUG', Default=false, cast=bool) Template_debug=DEBUG DATABASES= {    'default': Config ('Database_url', default='sqlite:///'+ Base_dir.child ('Db.sqlite3'), cast=Db_url)} Time_zone='America/sao_paulo'use_l10n=Trueuse_tz=True Secret_key= Config ('Secret_key') Email_host= Config ('Email_host', default='localhost') Email_port= Config ('Email_port', Default=25, cast=int) Email_host_password= Config ('Email_host_password', default="') Email_host_user= Config ('Email_host_user', default="') Email_use_tls= Config ('Email_use_tls', Default=false, cast=bool)# ...

Note that there are no defined parameters:

In the above example, SECRET_KEY = config(‘SECRET_KEY‘),在.env中 there is a default configuration parameter in addition to the one. if none ‘SECRET_KEY‘在 has been in the. env file, decouple will throw a undefinedvalueerror This strategy happens when you forget to configure an argument for unexpected behaviorThe most important files related to environment variables are described below: There are times when you don't want to change a parameter by using an. ini or. env file, starting with 3.0, decouple will follow the UNIX approach and the environment variable takes precedence over the configuration file variable; You can overwrite the variables of the configuration file:
Debug=true python manage.py

What is this principle?

There are 5 classes of decouple :

    • Config
      • Retrieving the location of the configuration file
    • Repositoryini
      • Reading values from the Os.environ,ini file in order
      • Note: The UNIX environment variable is higher than the profile variable starting from 3.0
    • Repositoryenv
      • Reading values from the Os.environ,.env file in order
      • Note: The UNIX environment variable is higher than the profile variable starting from 3.0
    • Repositoryshell
      • Just get the environment variables from the Os.environ
    • AutoConfig
      • Check the configuration you are using
      • It will search for Settings.ini or. env files recursively from your configuration module path

A simple example:

. evn file

user_info=rootport=3306ipadd=127.0.0.1switch=on

Pyton Parse File:

Import== config ('ipadd')print Ipadd

Detailed concrete usage can read bootcamp source code:

Https://github.com/vitorfs/bootcamp

Python-decouple Introduction

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.