[英]Avoiding code duplication in django settings files
I am following Django settings best practices by using base.py
, local.py
, prod.py
, and staging.py
.我使用
base.py
、 local.py
、 prod.py
和staging.py
遵循 Django 设置最佳实践。
My conundrum is whether or not to be okay with code duplication.我的难题是是否可以接受代码重复。 Let's take this example.
让我们举这个例子。 I need to set a URL which is used in a large dictionary of fixed values to configure a package.
我需要设置一个 URL,它用于大型固定值字典来配置 package。
local.py CONF_URL = 'hard coded local value'
prod.py CONF_URL = os.environ['CONF_URL']
staging.py CONF_URL = 'some other hard coded value'
I then have code like然后我有类似的代码
PACKAGE_CONF = {
'CONF_URL': CONF_URL,
'foo1': bar,
'foo2': bar,
'foo3': bar,
'foo4': bar,
'foo5': bar,
}
PACKAGE_CONF
in base.py
because we import base
from the leaf settings files and not the other way around.PACKAGE_CONF
放在base.py
中,因为我们从叶设置文件中导入base
而不是相反。PACKAGE_CONF
like using an env file but that seems unnecessarily complicated.PACKAGE_CONF
,比如使用 env 文件,但这似乎不必要地复杂。CONF_URL
from the environment but that's not a good local dev experience.CONF_URL
,但这不是一个好的本地开发体验。PACKAGE_CONF
in local
, staging,
and prod
.local
、 staging,
和prod
中复制PACKAGE_CONF
。 I'm not super pleased with any of these options.我对这些选项中的任何一个都不满意。 Can someone with experience in writing beautiful settings files offer a better solution?
有编写精美设置文件经验的人可以提供更好的解决方案吗?
You can use .env file for setting up the variables of local/dev environment, and ensure you have this same variables set up in staging/prod envs.您可以使用.env文件来设置本地/开发环境的变量,并确保您在 staging/prod 环境中设置了相同的变量。
.env file values will be used only when the environment var is not present. .env文件值仅在环境变量不存在时使用。 So, you can push the .env file to your code repo.
因此,您可以将.env文件推送到您的代码仓库。
In that way, you will be able to write just once your var in base.py file.这样,您将能够在base.py文件中只编写一次您的 var。
The solution I ended up doing is this我最终做的解决方案是这个
in base.py
I put在
base.py
我把
PACKAGE_CONF = {
'foo1': bar,
'foo2': bar,
'foo3': bar,
'foo4': bar,
'foo5': bar,
}
And then I override PACKAGE_CONF['CONF_URL']
in the leaf settings files, eg in staging.py然后我在叶子设置文件中覆盖
PACKAGE_CONF['CONF_URL']
,例如在 staging.py
CONF_URL = 'some other hard coded value'
PACKAGE_CONF['CONF_URL'] = CONF_URL
The downside is you might forget to add this value when you create a new leaf settings file and that may lead to unexpected behavior since the dictionary exists but one key is missing.缺点是您可能会在创建新的叶设置文件时忘记添加此值,这可能会导致意外行为,因为字典存在但缺少一个键。
However, I think this is acceptable since when you create a new leaf settings you usually copy paste an existing one.但是,我认为这是可以接受的,因为当您创建新的叶子设置时,您通常会复制粘贴现有的设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.