为什么我收到“KeyError: template_name”当序列化 Django Response 对象时?

发布于 2024-11-16 23:18:51 字数 3838 浏览 1 评论 0原文

缓存中间件必须腌制 Response 对象,但有时它会失败:

[...]/.virtualenvs/project/lib/python2.7/site-packages/django/template/response.py in __getstate__

    Ensures that the object can't be pickled before it has been
    rendered, and that the pickled state only includes rendered
    data, not the data used to construct the response.
    """
    obj_dict = self.__dict__.copy()
    if not self._is_rendered:
    raise ContentNotRenderedError('The response content must be rendered before it can be pickled.')

    del obj_dict['template_name'] ...

    KeyError: template_name

本地变量是:

Variable  Value
self  

u'Content-Language: fr\nExpires: Thu, 23 Jun 2011 17:40:18 GMT\nVary: Accept-Language, Cookie\nLast-Modified: Thu, 23 Jun 2011 11:40:18 GMT\nCache-Control: max-age=21600\nContent-Type: text/html; charset=utf...'

obj_dict  

{'_charset': 'utf-8',
 '_container': [u'\n\n\n\n\n<li>\n    <a href="/video/42506/outdoor-demo">\n        <img src="http://str2.site.com/4/2/5/0/6/42506/screenshots_80x80/4.jpg" />\n        <h3>Outdoor demo </h3>\n        <p>\n            <st...'],
 '_headers': {'cache-control': ['Cache-Control', 'max-age=21600'],
              'content-language': ['Content-Language', 'fr'],
              'content-type': ['Content-Type', 'text/html; charset=utf-8'],
              'expires': ['Expires', 'Thu, 23 Jun 2011 17:40:18 GMT'],
              'last-modified': ['Last-Modified',
                                'Thu, 23 Jun 2011 11:40:18 GMT'],
              'vary': ['Vary', 'Accept-Language, Cookie']},
 '_is_rendered': True,
 '_is_string': True,
 'cookies': {}}
    del obj_dict['context_data']
    del obj_dict['_post_render_callbacks']
    return obj_dict
    def resolve_template(self, template):

问题不会一直发生,并且我不确定,但我认为它是当使用 AJAX 调用时,仅与一种类型的视图相关。这是一个示例视图:

class CategoriesView(ChunkTemplateResponseMixin, generic.ListView):
    """
        List categories
    """
    template_name = 'app/categories.html'
    context_object_name = 'categories'
    paginate_by = 10
    model = Tag
    chunk_template_name = 'app/categories_chunk.html'
    chunk_marker = 'chunk'

    def get_queryset(self): 
        """
            Return the categ by usage, removing categs with no videos on the
            current site
        """

        categs = []
        videos = Video.on_site.all()
        for tag in Video.tags_set.usage():
            if Video.tagged.with_all(tag, videos).count() > 25:
                categs.append(tag)

        return categs

这显然是所有失败视图的共同点:

class ChunkTemplateResponseMixin(TemplateResponseMixin):
    """
        Return a different template if the request pass a parameter.

        If all request are in ajax and you still want to differentiate
        page loaded entirely from chunk, set chunk marker to a string
        that enable the alternate template rendering when found in
        GET or POST.

        eg: /categories => normal template
            /categories?chunk=True => chunk template

    """

    chunk_marker = None
    chunk_template_name = None

    def is_chunk(self):
        """
            Check if the template chunk should be rendered instead of
            the original one.
        """

        if self.chunk_marker:
            return self.chunk_marker in self.request.REQUEST
        return self.request.is_ajax()


    def render_to_response(self, *args, **kwargs):

        if self.is_chunk():
            self.template_name = self.chunk_template_name

        return super(ChunkTemplateResponseMixin, 
                      self).render_to_response(*args, **kwargs)

我猜有一些与其 TemplateResponseMixin 父级相关的东西 但我确实在孩子身上设置了 template_name在此处输入代码

The cache middleware must pickle the Response object but sometime when it does, it fails:

[...]/.virtualenvs/project/lib/python2.7/site-packages/django/template/response.py in __getstate__

    Ensures that the object can't be pickled before it has been
    rendered, and that the pickled state only includes rendered
    data, not the data used to construct the response.
    """
    obj_dict = self.__dict__.copy()
    if not self._is_rendered:
    raise ContentNotRenderedError('The response content must be rendered before it can be pickled.')

    del obj_dict['template_name'] ...

    KeyError: template_name

The local vars are:

Variable  Value
self  

u'Content-Language: fr\nExpires: Thu, 23 Jun 2011 17:40:18 GMT\nVary: Accept-Language, Cookie\nLast-Modified: Thu, 23 Jun 2011 11:40:18 GMT\nCache-Control: max-age=21600\nContent-Type: text/html; charset=utf...'

obj_dict  

{'_charset': 'utf-8',
 '_container': [u'\n\n\n\n\n<li>\n    <a href="/video/42506/outdoor-demo">\n        <img src="http://str2.site.com/4/2/5/0/6/42506/screenshots_80x80/4.jpg" />\n        <h3>Outdoor demo </h3>\n        <p>\n            <st...'],
 '_headers': {'cache-control': ['Cache-Control', 'max-age=21600'],
              'content-language': ['Content-Language', 'fr'],
              'content-type': ['Content-Type', 'text/html; charset=utf-8'],
              'expires': ['Expires', 'Thu, 23 Jun 2011 17:40:18 GMT'],
              'last-modified': ['Last-Modified',
                                'Thu, 23 Jun 2011 11:40:18 GMT'],
              'vary': ['Vary', 'Accept-Language, Cookie']},
 '_is_rendered': True,
 '_is_string': True,
 'cookies': {}}
    del obj_dict['context_data']
    del obj_dict['_post_render_callbacks']
    return obj_dict
    def resolve_template(self, template):

The problem doesn't occur all the time, and I'm not sure, but I think it's related only to one type of view when it's called with AJAX. Here is an example view:

class CategoriesView(ChunkTemplateResponseMixin, generic.ListView):
    """
        List categories
    """
    template_name = 'app/categories.html'
    context_object_name = 'categories'
    paginate_by = 10
    model = Tag
    chunk_template_name = 'app/categories_chunk.html'
    chunk_marker = 'chunk'

    def get_queryset(self): 
        """
            Return the categ by usage, removing categs with no videos on the
            current site
        """

        categs = []
        videos = Video.on_site.all()
        for tag in Video.tags_set.usage():
            if Video.tagged.with_all(tag, videos).count() > 25:
                categs.append(tag)

        return categs

Here is apparently the common denominator to all the views failling:

class ChunkTemplateResponseMixin(TemplateResponseMixin):
    """
        Return a different template if the request pass a parameter.

        If all request are in ajax and you still want to differentiate
        page loaded entirely from chunk, set chunk marker to a string
        that enable the alternate template rendering when found in
        GET or POST.

        eg: /categories => normal template
            /categories?chunk=True => chunk template

    """

    chunk_marker = None
    chunk_template_name = None

    def is_chunk(self):
        """
            Check if the template chunk should be rendered instead of
            the original one.
        """

        if self.chunk_marker:
            return self.chunk_marker in self.request.REQUEST
        return self.request.is_ajax()


    def render_to_response(self, *args, **kwargs):

        if self.is_chunk():
            self.template_name = self.chunk_template_name

        return super(ChunkTemplateResponseMixin, 
                      self).render_to_response(*args, **kwargs)

I'm guessing there is something related to it's TemplateResponseMixin parent
but I do set template_name on the child. enter code here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文