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

标签 python django multithreading

我正在根据请求的主机名更改中间件中的默认 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/

相关文章:

c# - 无效操作异常 : The calling thread cannot access this object because a different thread owns it.

c++ - 如何将指向类方法的指针传递给 boost 线程

python - 从单个输入语句分配多个值,忽略空格

python - 保护 Typeform Webhook Python

python - 如何动态更改 tkinter 中按钮的文本?

mysql - Django 南 : Changing the type of primary key of existing table which are referenced by FK

html - 将值从 Django View 传递到 AngularJS 插入的模板

java - 使用 ThreadPoolExecutor() 只运行一个线程

python - 如何使用Python控制Chrome

python - 为训练 Tensorflow 网络提供 spark 数据帧的最佳实践