我正在研究django中间件代码库。我查看了下面的图表

所以,这张图很清楚。
但我有一些问题
process_view() of AuthenticationMiddleware中,那么会调用process_response() of MessageMiddleware吗?process_view() of AuthenticationMiddleware返回响应,那么会调用MessageMiddleware的process_response()吗?或者它将从AuthenticationMiddleware返回(即调用process_response() of AuthenticationMiddleware,但不会调用process_response() of MessageMiddleware)在使用新样式中间件类的1.10中,我调试了django的行为,但我不熟悉旧的MIDDLEWARE_CLASSES设置?
对于django 1.10:- 1)如果process_request() For AuthenticationMiddleware返回响应,那么process_template_response()和process_response()将被调用,如下图所示,用于所有中间件。
2)如果process_request() for AuthenticationMiddleware引发异常,则行为也将相同。
如果我错了,请纠正我。
提前谢谢。
发布于 2020-11-25 06:49:26
如果您在1.10版本之前处理django项目,正式文件可以回答您的第一个问题。
请阅读段落:使用中间件和MIDDLEWARE_CLASSES之间的行为差异
在MIDDLEWARE_CLASSES下,每个中间件都会被调用其process_response方法,即使早期的中间件通过从其process_request方法返回响应而短路。在中间件下,中间件的行为更像洋葱:响应在输出过程中经过的层与看到请求进入的层相同。如果一个中间件短路了,只有中间件和它之前的中间件才会看到响应。
但是,自从django v1.10之后,MIDDLEWARE_CLASSES就被删除了,并且从那时起引入了新的中间件工作流样式(使用__call__() ),这允许每个中间件(在MIDDLEWARE中应用)通过返回响应返回(带有错误状态)并在异常处理时不调用后续中间件和查看中间件来内部确定是否短路,在这种情况下,问题中的关系图可能并不总是这样,特别是如果您的项目包括自定义中间件。
附带注意,在异常上短路的中间件可能如下所示:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
try:
# Code to be executed for each request before
# the view (and later middleware) are called.
do_something_but_raise_exception()
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
except WHATEVER_EXCEPTION as e:
# short-circuiting, because self.get_response() is not invoked,
response = generate_custom_response(e)
return response旁注
就其价值而言,FastAPI中的中间件也是以类似的方式构造的。
发布于 2019-03-07 09:27:00
对,你是对的。函数convert_exception_to_response()将捕获process_request()引发的异常。
见资料来源:
https://github.com/django/django/blob/master/django/core/handlers/base.py https://github.com/django/django/blob/master/django/core/handlers/exception.py
https://stackoverflow.com/questions/49365722
复制相似问题