简体   繁体   English

Python中配置变量的最佳实践

[英]Best practice for config variables in Python

So recently my programs have become more complex, and are starting to require more configuration. 所以最近我的程序变得越来越复杂,并且开始需要更多配置。 I've been doing the following, however it feels wrong... 我一直在做以下,但感觉不对......

class config:
    delay = 1.3
    files = "path/to/stuff"
    name = "test"

dostuff(config.name) #etc...

I've never been a fan of the ALL_CAPS_VARIABLE method, and was wondering if there is an "official" way to do this, and if there is anything wrong with my current method. 我从来没有成为ALL_CAPS_VARIABLE方法的粉丝,并且想知道是否有“官方”方法来做到这一点,以及我当前的方法是否有任何问题。

I recommend use of python-decouple . 我建议使用python-decouple This library allow separate code from configurations(data). 该库允许单独的代码与配置(数据)。

UPDATE: 更新:

Brief explanation of usage of this library: 该库的用法简要说明:

Simply create a .env text file on your repository's root directory in the form: 只需在存储库的根目录中以下列形式创建.env文本文件:

DEBUG=True
TEMPLATE_DEBUG=True
EMAIL_PORT=405
SECRET_KEY=ARANDOMSECRETKEY
DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase
PERCENTILE=90%
#COMMENTED=42

OBS: put *.env in your .gitignore OBS:*.env放在你的.gitignore

On your python code, can be used in this way: 在你的python代码上,可以这样使用:

from decouple import config

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM