Django对于立即的HTTP响应是否有例外? [英] Does Django have exception for an immediate http response?

查看:40
本文介绍了Django对于立即的HTTP响应是否有例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django-Tastypie具有 ImmediateHttpResponse 异常,该异常允许立即返回客户端:

Django-Tastypie has ImmediateHttpResponse exception which allow to return to the client an immediate response:

raise ImmediateHttpResponse(response='a message')

Django具有 Http404 ,但是我找不到像 ImmediateHttpResponse 这样的更通用的异常.

Django has Http404, but i couldn't find a more universal exception like ImmediateHttpResponse.

您使用什么技术立即向客户返回400响应?

What technique do you use to return to client an immediate 400 response?

例如具有模型:

class Subscriber(Model):

    def delete(self, *args, **kwargs):
        raise ImmediateHttpResponse('Deleting subcribers is not allowed!')

并尝试删除对象将向客户端返回带有给定消息的 400 响应.

and trying to delete an object would return to the client a 400 response with the given message.

推荐答案

我认为您想要的是中间件,它实现了 process_exception .

I think what you want is a middleware which implements a process_exception.

它的工作原理是:您在视图上引发Exception(例如InstantHttpResponse).如果您的中间件捕获到该异常,则中间件将返回一个响应,在您的情况下,其状态为400.如果您未捕获到该异常,则Django最终将捕获它,并返回状态500(服务器错误),或其他状态.

It works like this: you raise an Exception on you view (e.g. ImmediateHttpResponse). If the exception is catched by your middleware, the middleware returns a response, in your case the with a status 400. If you don't catch the exception, Django will catch it in the end, returning a status 500 (server error), or other status.

最简单的示例是捕获Http404的中间件.如果在中间件中捕获到异常Http404,则可以返回所需的任何响应(状态200、400等).如果您没有捕获(即中间件的process_exception方法返回None),则Django会为您捕获它并返回状态为404的Response.这实际上是具有您要在其中进行响应的自定义异常的标准方式一种自定义方式.

The simplest example is a middleware that catches Http404. If you catch the exception Http404 in your middleware, you can return any response you want (status 200, 400, etc). If you don't catch (i.e. the process_exception method of you middleware returns None), Django will catch it for you and return a Response with status 404. This is actually the standard way of having your own custom exceptions that you want to respond in a custom way.

这篇关于Django对于立即的HTTP响应是否有例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆