简体   繁体   中英

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.

I recommend use of 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:

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

On your python code, can be used in this way:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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