我正在使用Google App Engine(Python)中的webapp2框架。在webapp2 exception handling: exceptions in the WSGI app中,它描述了如何处理函数中的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 error page上,您可以看到您的用户名。我想在我的网站的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)
答案 0 :(得分:3)
错误处理程序和请求处理程序可调用程序的调用约定是不同的:
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
中隐藏额外的异常参数。