我试图让 Django 中的一些配置设置在运行时自动确定。
我已经设置了一个中间件处理程序,它在发出第一个请求之前运行一次,然后通过引发 MiddlewareNotUsed 来禁用自身。当处理程序运行时,它会通过 HTTP 从另一台服务器中提取一些信息。我希望该信息可供所有 View 使用。
在设置模块中,我有一个空字符串。我认为我可以使用检索到的信息动态修改它,以便所有 View 都可以使用它。但是当我从中间件处理程序更新字符串时,信息不知何故丢失了。 View 只能看到空字符串。
我如何使通过 HTTP 检索的信息可用于所有 View ?
我想将其保存在内存中,而不是数据库或文件系统中,但如果那是唯一的选择,我将使用这些选项之一。
最佳答案
好吧,我做过一次类似的事情,但我并不为此感到骄傲:)
但这很简单并且完成了工作,所以这里是:
from django.conf import settings
class SomeMiddleware(object):
def process_request(self, request):
try:
settings.SOME_STRING_CONFIG
except AttributeError:
settings.SOME_STRING_CONFIG = some_value_to_set
但是,这不是处理 django.settings 的好方法,参见 https://docs.djangoproject.com/en/dev/topics/settings/#altering-settings-at-runtime .
不,让我在这里引用它:
Altering settings at runtime
You shouldn't alter settings in your applications at runtime. For example, don't do this in a view:from django.conf import settings
settings.DEBUG = True # Don't do this!The only place you should assign to settings is in a settings file.
(我加了粗体)
关于python - Django 中的动态配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10341847/