为什么django的设置对象是一个LazyObject? [英] Why is django's settings object a LazyObject?

查看:358
本文介绍了为什么django的设置对象是一个LazyObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class LazySettings(LazyObject):
...

使设置对象懒惰的原因是什么?

解决方案

查看本节的Django编码风格。原因在此解释(下面引用)。



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


模块不应该通常使用存储在
django.conf中的设置在顶层设置(即当导入模块
时进行评估)。对此的解释如下:



手动配置设置(即不依赖于
DJANGO_SETTINGS_MODULE环境变量)是允许和可能的
作为如下:

 从django.conf导入设置

settings.configure({},SOME_SETTING ='foo')但是,如果在settings.configure行之前访问了
的任何设置,这将无法正常工作。
(在内部,设置是一个LazyObject,如果尚未配置
,则会自动配置
)。



所以,如果有一个模块包含一些代码如下:

 从django.conf导入设置
从django.core.urlresolvers import get_callable

default_foo_view = get_callable(settings.FOO_EXAMPLE_VIEW)

...然后导入
此模块将导致设置对象进行配置。那
意味着第三方在
顶级导入模块的能力与手动配置
对象的能力是不相容的,或者在某些情况下非常困难。 / p>

代替上述代码,一个懒惰或间接级别必须是
,例如 django.utils.functional.LazyObject
django.utils.functional.lazy() lambda 。 / p>


Looking in django.conf I noticed that settings are implemented like this:

class LazySettings(LazyObject):     
...

What is the rationale behind making settings objects lazy?

解决方案

Check out this section of the Django coding style. The reason is explained in there (quoted below).

In addition to performance, third-party modules can modify settings when they are imported. Accessing settings should be delayed to ensure this configuration happens first.

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.

这篇关于为什么django的设置对象是一个LazyObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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