0

我正试图围绕一个正确、可行的process_view. 这个想法是在process_view. 我的问题主要是如何处理视图函数中的异常。

据我了解,中间件函数可能永远不会引发异常,因此必须捕获视图函数可能引发的所有异常。这种理解在实践中确实得到了证实:如果我没有捕捉到异常,Django 的基本处理程序将跳过任何 process_exception 调用。但是,如果我确实捕获了异常,视图函数将被调用两次(一次由我的中间件调用,一次由基本处理程序调用,以尝试遇到异常,以便它可以由各种中间件处理process_exception)。在下面的代码片段中,第一个调用是 in response = middleware_method(...,第二个调用是 in response = callback(...

来自 Django 1.4 的 django/core/handlers/base.py 的片段:

    # Apply view middleware
    for middleware_method in self._view_middleware:
        response = middleware_method(request, callback, callback_args, callback_kwargs)
        if response:
            break

if response is None:
    try:
        response = callback(request, *callback_args, **callback_kwargs)
    except Exception, e:
        # If the view raised an exception, run it through exception
        # middleware, and if the exception middleware returns a
        # response, use that. Otherwise, reraise the exception.
        for middleware_method in self._exception_middleware:
            response = middleware_method(request, e)
            if response:
                break
        if response is None:
            raise

为了更加清楚,这是我的中间件:

class MyMiddleware(object):

    def process_view(self, request, view_func, view_args, view_kwargs):
        # ... do stuff

        try:
            response = view_func(request, *view_args, **view_kwargs)
        except:
            return None

        # or, alternatively (but this has its own set of problems)
        response = view_func(request, *view_args, **view_kwargs)

        # do more stuff
4

0 回答 0