Is Django middleware thread safe?

给你一囗甜甜゛ 提交于 2019-12-18 19:02:28

问题


Are Django middleware thread safe? Can I do something like this,

class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        self.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        # will self.thread_safe_variable always equal to some_dynamic_value_from_request?

回答1:


Why not bind your variable to the request object, like so:

class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        request.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        #... do something with request.thread_safe_variable here ...



回答2:


No, very definitely not. I write about this issue here - the upshot is that storing state in a middleware class is a very bad idea.

As Steve points out, the solution is to add it to the request instead.




回答3:


If you're using mod_wsgi in daemon mode with multiple threads, none of these options will work.

WSGIDaemonProcess domain.com user=www-data group=www-data threads=2

This is tricky because it will work with the django dev server (single, local thread) and give unpredictable results in production depending on your thread's lifetime.

Neither setting the request attribute nor manipulating the session is threadsafe under mod_wsgi. Since process_response takes the request as an argument, you should perform all of your logic in that function.

class ThreadsafeTestMiddleware(object):

    def process_response(self, request, response):
        thread_safe_variable = request.some_dynamic_value_from_request


来源:https://stackoverflow.com/questions/6214509/is-django-middleware-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!