python - Django 中的动态配置

标签 python django web-services

我试图让 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/

相关文章:

python - 在 python 中调用函数链的更好方法?

python - 如何将解包运算符 ("*") 与 C 风格字符串格式一起使用?

python - 添加额外的参数到serializer.data

javascript - ajax 调用 web 服务总是会导致错误

python - 属性错误 : Cannot access callable attribute 'groupby' of 'DataFrameGroupBy' objects

python - 年到世纪功能

django - gunicorn 找不到 django wsgi 模块

python - 如何在 django 2.0 admin 中使用 allow_tags?

c# - 使用 c# webservice 下载大文件

c# - asp.net asmx Web 服务返回 xml 而不是 json