【发布时间】:2013-09-03 10:33:08
【问题描述】:
我正在审查 Django 的 TemplateView,因为我们在使用 AJAX 从单个网页同时调用同一服务时看到了线程问题。
这些症状是您对与服务器上的请求/响应相关的线程问题所期望的。有时我们期望从第一次调用中得到的值会同时返回给第一次和第二次调用,有时它会颠倒过来,有时它会按预期工作。如果我们序列化 AJAX 调用,结果总是正确的。
看代码,看到TemplateView继承自TemplateResponseMixin,实现如下:
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
)
因此,TemplateView 需要一个名为 self.request 的实例变量。如果给定的 TemplateView 子类实例用于处理并发请求,我想您会看到我们所看到的行为。
我说得对吗?关于处理并发请求,我还没有探索过 Django 的线程模型。如果他们的线程模型与我使用过的每个 Java Servlet 引擎中使用的模型相似,那么我想不出一种不会破坏它的方法。如果 Django 做了一些花哨的事情,比如使用 TemplateView 实例池来处理并发请求,或者它做了一些基本的事情,比如排队请求,那么我找错地方了,我们需要寻找其他地方来解决我们的线程问题。
提前感谢您的帮助。
【问题讨论】:
-
您应该为此视图发布 urls.py 条目。
标签: python django multithreading django-templates django-views