Jonathan Blackburn
Jonathan Blackburn

Reputation: 518

Django TemplateView thread safety

I'm reviewing Django's TemplateView because of a threading problem we're seeing while calling the same service concurrently using AJAX from a single web page.

The symptoms are what you'd expect with a threading problem related to requests/responses on the server. Sometimes the value we'd expect from the first invocation is returned to both the first and the second, sometimes it's reversed, sometimes it works as expected. If we serialize the AJAX calls, the results are always correct.

Looking at the code, I see that TemplateView inherits from TemplateResponseMixin, which has the following implementation:

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.

    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

So, TemplateView requires an instance variable called self.request. If a given TemplateView subclass instance is used to serve concurrent requests, I imagine you'd see the behavior we're seeing.

Am I right about this? I have not explored Django's threading model with respect to handling concurrent requests. If their threading model is similar to that used in every Java Servlet engine I've worked with, then I can't think of a way that this isn't broken. If Django does something fancy like using a pool of TemplateView instances to handle concurrent requests, or it does something rudimentary like queuing requests, then I'm looking in the wrong place and we need to look elsewhere to fix our threading problem.

Thanks in advance for your help.

Upvotes: 0

Views: 219

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55293

There is one view instance per request, you can find the code that does this in the implementation of View.as_view (this is what you call in the URL conf).

Some Template Tags, however, are not thread safe.

To help you further though, I think you'd need to tell us more about the exact issue you're seeing. You might also want to tell us what technology you're using to serve requests - is that mod_wsgi, Gunicorn, something else?

Upvotes: 4

Related Questions