gpt4 book ai didi

python - 在中间件中通过 set_urlconf 和 request.urlconf 修改 Django urlconf 是否安全?

转载 作者:行者123 更新时间:2023-12-03 12:48:29 25 4
gpt4 key购买 nike

我正在根据请求的主机名更改中间件中的默认 urlconf,它在开发过程中按预期工作,但是我担心在运行时修改 Django 设置时出现竞争/线程问题!

我担心 Django 会将 urlconfs 与许多并发请求混淆。这是一个合理的担忧吗?

最佳答案

TLDR 版本

您真的不需要在中间件中使用 set_urlconf。不过,您可以自由设置 request.urlconf 而不必担心线程。

对于 django 处理的每个请求,它将使用 ROOT_URLCONFrequest.urlconf 的值(如果它已在中间件中设置)来决定将什么 urlconf使用。因此,您不需要使用 set_urlconf。设置 request.urlconf 是推荐的方式。

工作原理

事实上,在幕后,请求通过中间件后,django 调用此函数来决定使用哪个 urlconf,因此如果设置了 request.urlconf,则任何调用中间件中的 set_urlconf 无论如何都是无关紧要的:

# django.core.handlers.base.py

def resolve_request(self, request):
if hasattr(request, 'urlconf'):
urlconf = request.urlconf
set_urlconf(urlconf)
resolver = get_resolver(urlconf)

结帐 how django proceeses a request从官方文档获取更多信息。

set_urlconf的线程安全

另请注意,set_urlconf 的实现是线程安全的:

# django.urls.base.py

# Overridden URLconfs for each thread are stored here.
_urlconfs = Local()


def set_urlconf(urlconf_name):
"""
Set the URLconf for the current thread (overriding the default one in
settings). If urlconf_name is None, revert back to the default.
"""
if urlconf_name:
_urlconfs.value = urlconf_name
else:
if hasattr(_urlconfs, "value"):
del _urlconfs.value

(也就是说,它只影响当前线程。)

关于python - 在中间件中通过 set_urlconf 和 request.urlconf 修改 Django urlconf 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66039222/

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