在请求处理程序类方法而不是函数中处理 webapp2 404 错误



我在Google App Engine(Python)中使用webapp2框架。在 webapp2 异常处理:WSGI 应用程序中的异常中,描述了如何处理函数中的 404 错误:

import logging
import webapp2
def handle_404(request, response, exception):
    logging.exception(exception)
    response.write('Oops! I could swear this page was here!')
    response.set_status(404)
def handle_500(request, response, exception):
    logging.exception(exception)
    response.write('A server error occurred!')
    response.set_status(500)
app = webapp2.WSGIApplication([
    webapp2.Route('/', handler='handlers.HomeHandler', name='home')
])
app.error_handlers[404] = handle_404
app.error_handlers[500] = handle_500

如何在webapp2.RequestHandler类的.get()方法中处理该类中的 404 错误?

编辑:

我想调用RequestHandler的原因是访问会话(request.session)。否则,我无法将当前用户传递给 404 错误页面的模板。即在 StackOverflow 404 错误页面上,您可以看到您的用户名。我还想在网站的 404 错误页面上显示当前用户的用户名。这在函数中是可能的还是必须是RequestHandler

根据@proppy的答案更正代码:

class Webapp2HandlerAdapter(webapp2.BaseHandlerAdapter):
    def __call__(self, request, response, exception):
        request.route_args = {}
        request.route_args['exception'] = exception
        handler = self.handler(request, response)
        return handler.get()
class Handle404(MyBaseHandler):
    def get(self):
        self.render(filename="404.html",
            page_title="404",
            exception=self.request.route_args['exception']
        )
app = webapp2.WSGIApplication(urls, debug=True, config=config)
app.error_handlers[404] = Webapp2HandlerAdapter(Handle404)

错误处理程序和请求处理程序可调用对象的调用约定不同:

  • error_handlers需要(request, response, exception)
  • RequestHandler需要(request, response)

您可以使用类似于Webapp2HandlerAdapter的内容来使webapp2.RequestHandler适应可调用对象。

class Webapp2HandlerAdapter(BaseHandlerAdapter):
    """An adapter to dispatch a ``webapp2.RequestHandler``.
    The handler is constructed then ``dispatch()`` is called.
    """
    def __call__(self, request, response):
        handler = self.handler(request, response)
        return handler.dispatch()

但是您必须在请求route_args中潜入额外的异常参数。

最新更新