python - Django:如何在模板渲染期间捕获基于类的 View 中的特定异常?

标签 python django django-templates

在基于类的 View 中呈现 Django 模板期间如何捕获特定异常?

我有一个自定义异常 ImmediateHttpResponse,它旨在在我的基于类的 View 中引起立即重定向。我试过:

def dispatch(self, *args, **kwargs):
    try:
        return super(AppConnectionsView, self).dispatch(*args, **kwargs)
    except ImmediateHttpResponse as e:
        return HttpResponseRedirect(e.response)

我试图捕获的异常是在模板标记中引发的,因此似乎该异常被 django 的模板调试拦截,并且我收到模板渲染错误 HttpResponseRedirect no exception supplied。我仍然想调试我的模板,只是在引发 HttpResponseRedirect 时不想调试。

请保留所有关于不在模板标签中引发错误的评论......我有一个非常充分的理由。

最佳答案

如果您真的必须不惜一切代价这样做,这里有一个简单的解决方案:

def dispatch(self, *args, **kwargs):
    response = super(AppConnectionsView, self).dispatch(*args, **kwargs)
    try:
        response.render()
    except ImmediateHttpResponse as e:
        return HttpResponseRedirect(e.response)
    return response

之所以无法在 View 中捕获渲染错误,是因为尽管在 View 中创建了响应,但它实际上是由BaseHandler 渲染的。 ,它会适本地处理所有错误。上述解决方案的缺点是每次请求都会渲染模板两次。

能够捕获自定义错误的唯一其他方法是自定义 BaseHandler(或者它的派生物,如 WSGIHandler),这显然会消除双重渲染问题。

假设您正在使用 wsgi,您可能应该这样做 :) 您可以这样做:

import django
from django.utils import six
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIHandler
from my_app.exceptions import ImmediateHttpResponse

class WSGIHandler(DjangoWSGIHandler):
    def handle_uncaught_exception(self, request, resolver, exc_info):
        (type, value, traceback) = exc_info
        if type is not None and issubclass(type, ImmediateHttpResponse):
            six.reraise(*exc_info)
        return super(WSGIHandler, self).handle_uncaught_exception(
            request, resolver, exc_info)

def get_wsgi_application():
    django.setup()
    return WSGIHandler()

现在你可以在wsgi.py中使用这个函数了:

application = get_wsgi_application()

关于python - Django:如何在模板渲染期间捕获基于类的 View 中的特定异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27210643/

相关文章:

python - 带有 flat=True 的 Values_list 仍显示括号

python - Image.fromarray 只产生黑色图像

python - 使用 __del__ 在清理文件中保存状态?

python - Azure Python 网站不对 URL 中的空格进行 URL 解码

django - Controller 逻辑和模板逻辑,分页在哪里划线?

python - 如何模拟死亡率并将其可视化为随着时间推移而消失的点

python - 以编程方式在 django ModelForm 中设置排除字段的值

django - 为什么此代码仅对 super 用户返回 true

python - Django Admin - 表格内联外键字段列表的动态值

django 'thumbnail' 不是有效的标签库 :