简体   繁体   English

为自定义 django 模块定义默认应用程序设置的最佳实践?

[英]Best practice for defining default app settings for custom django module?

Is there a defined best practice for defining custom settings that come with a django app.是否有定义 django 应用程序附带的自定义设置的最佳实践。

What I have at the moment is a separate file called app_settings.py that looks like this:我目前拥有的是一个名为app_settings.py的单独文件,如下所示:

from django.conf import settings

# MY_SETTING_1 is required and will brake the application if not defined
try:
    MY_SETTING_1 = str(getattr(settings, 'MY_SETTING_1'))
except AttributeError:
    raise ImproperlyConfigured ('MY_SETTING_1 not defined in settings.py.')


# MY_SETTING_2 is not required and has a default value
MY_SETTING_2 = getattr(settings, 'MY_SETTING_2', ['default_value'])

Then I am importing this in my views.py , and using it like this:然后我将它导入到我的views.py中,并像这样使用它:

from my_app import app_settings

print (app_settings.MY_SETTING_1)
print (app_settings.MY_SETTING_2)

This works ok, but I am not quite happy with the design.这工作正常,但我对设计不太满意。 I am assuming that I can somehow use the class defined in apps.py , but I am not sure how.我假设我可以以某种方式使用apps.py中定义的类,但我不确定如何使用。

Is there a best (or better) practice for this?对此有最佳(或更好)的做法吗?

You could try https://pypi.org/project/typed_app_settings/ .您可以尝试https://pypi.org/project/typed_app_settings/

Example:例子:

# my_app/app_settings.py
from typed_app_settings import UndefinedValue, typed_app_settings_dict

@typed_app_settings_dict("MY_APP")
class Settings:
    MY_SETTING_1: str = UndefinedValue()
    MY_SETTING_2: str = "default_value"

settings = Settings()

Then in the view you would just use it like this.然后在视图中你会像这样使用它。

from my_app.app_settings import settings

print(app_settings.MY_SETTING_1)
print(app_settings.MY_SETTING_2)

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

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