Django设置:引发KeyError,引发ImproperlyConfigured或使用默认值? [英] Django settings: raise KeyError, raise ImproperlyConfigured or use defaults?

查看:81
本文介绍了Django设置:引发KeyError,引发ImproperlyConfigured或使用默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django希望您使用 settings.py 中的环境变量来适应多种环境(例如本地,heroku,AWS).

Django expects you to use environment variables in settings.py to adapt to multiple environments (e.g. local, heroku, AWS).

我想我应该在环境变量 DB_USERNAME 中定义数据库的用户名.我应该怎么读?

I guess I should define -for instance- the username of the DB in an environment variable DB_USERNAME. How should I read it?

import os
DB_USERNAME = os.environ['DB_USERNAME']
DB_USERNAME = os.environ.get('DB_USERNAME')
DB_USERNAME = os.environ.get('DB_USERNAME', 'john')

我应该捕获KeyError并引发一个我自己配置​​不正确?我宁愿让应用程序停止运行,也不愿使用不正确的设置(默认设置,人们忘记设置变量等)运行它.

Should I capture the KeyError and raise a ImproperlyConfigured myself? I prefer to make the app stop rather than run it using incorrect settings (defaults, people forgetting to set a variable,etc).

在使用默认值的情况下,甚至可能会出现john散居和远程存在但具有不同权限的情况.看起来不太坚固.

In the case of the defaults, it might even happen that john exists both loaclly and remotely, but with different permissions. It doesn't look very robust.

推荐答案

我建议您采用不同的方法进行工作.

I would suggest a different approach to what you are doing.

我使用以下过程:

  1. 使用环境变量创建一个 .env .ini 文件:

DB_USERNAME=myDB
A_NUMBER=1
ALLOWED_HOSTS=localhost, 127.0.0.1, my_host
DEBUG=False
MY_DJANGO_KEY=no_peeking_this_is_secret

  • 使用 decouple.config -这将使您的生活更轻松-可以阅读 .env / .ini 文件:

    settings.py 上:

    from decouple import Csv, config
    
    DEBUG = config('DEBUG', cast=bool, default=True)
    A_NUMBER = config('A_NUMBER') # No cast needed!
    ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv(), default='')
    ...
    

  • 这将允许您为每个可能的配置拥有多个 .env .ini 文件,而您不必担心混淆权限等.

    That will allow you to have multiple .env or .ini files for each of your possible configurations and you won't have to worry about mixing up permissions etc.

    最后,我倾向于使用默认设置,并尽可能降低配额(例如,查看我的默认允许的主机,它是一个空字符串).
    但是,如果存在一些必须正确设置的非常重要的变量,则:

    Finally, I tend to use defaults with the lowest allowances possible (ex. look at my default allowed hosts which is an empty string).
    But if there exists some very important variable that must be set correctly, then:

    • 如果未定义变量且未设置默认值,则 config()方法将引发 UndefinedValueError .

    因此,我们可以创建一个 try:...例外:块来预期:

    We can therefore create a try:... except: block to anticipate that:

    try:
        SUPER_IMPORTANT_VAR = config('SUPER_IMPORTANT_VAR')
    except UndefinedValueError:
        print('Hey!! You forgot to set SUPER_IMPORTANT_VAR!!')
    

    这篇关于Django设置:引发KeyError,引发ImproperlyConfigured或使用默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆