gpt4 book ai didi

python - 为什么django的设置对象是一个LazyObject?

转载 作者:太空狗 更新时间:2023-10-29 22:16:34 27 4
gpt4 key购买 nike

查看 django.conf 我注意到设置是这样实现的:

class LazySettings(LazyObject):     
...

使设置对象惰性化背后的基本原理是什么?

最佳答案

查看 this section Django 编码风格。原因在那里解释(引用如下)。

除了性能之外,第三方模块在导入时可以修改设置。应延迟访问设置以确保首先发生此配置。

Modules should not in general use settings stored in django.conf.settings at the top level (i.e. evaluated when the module is imported). The explanation for this is as follows:

Manual configuration of settings (i.e. not relying on the DJANGO_SETTINGS_MODULE environment variable) is allowed and possible as follows:

from django.conf import settings

settings.configure({}, SOME_SETTING='foo')

However, if any setting is accessed before the settings.configure line, this will not work. (Internally, settings is a LazyObject which configures itself automatically when the settings are accessed if it has not already been configured).

So, if there is a module containing some code as follows:

from django.conf import settings
from django.core.urlresolvers import get_callable

default_foo_view = get_callable(settings.FOO_EXAMPLE_VIEW)

...then importing this module will cause the settings object to be configured. That means that the ability for third parties to import the module at the top level is incompatible with the ability to configure the settings object manually, or makes it very difficult in some circumstances.

Instead of the above code, a level of laziness or indirection must be used, such as django.utils.functional.LazyObject, django.utils.functional.lazy() or lambda.

关于python - 为什么django的设置对象是一个LazyObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11238514/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com