English 中文(简体)
在请求处理器类方法中处理 Webapap2 404 错误, 而不是在函数中处理
原标题:Handle webapp2 404 error in requesthandler class method instead of in a function

我在谷歌 App 引擎( Python) 中使用 Webap2 框架。 在 < a href=" http://webapp- improped. appspot.com/ guide/ explications.html# 例外- in-the-wsgi- app" rel= “ nofollow noreferrer” >webap2 例外处理: 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

该类中 .get () 方法中的 webapp2. requestHandler 类中, 我如何处理404个错误?

<强>编辑:

我想拨打 requestHandler 的原因是要访问会话( request.session ) 。 否则我就无法将当前用户传送到404错误页面的模板。 也就是说, < a href=" https:// stackoverflow. com/ abc > > > StackOverflow 404错误页面 您可以看到您的用户名 。 我想将当前用户的用户名显示在我的网站 s 404 错误页面上。 这在函数中是可能的, 还是必须显示为 < code> suggestHandler ?

以 @ proppy s 回答 : 为基础的 < proppy s ans answer: 更正代码

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)
最佳回答
问题回答

暂无回答




相关问题
How to make logging.debug work on Appengine?

I m having a tough time getting the logging on Appengine working. the statement import logging is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an ...

gqlQuery returns object, want list of keys

Is there a way to convert the GqlQuery object to an array of keys, or is there a way to force the query to return an array of keys? For example: items = db.GqlQuery("SELECT __key__ FROM Items") ...

Integrating Google AppEngine with a Thick Client

I want to make a multi-user client-server solution with Java Swing thick client as a front-end and Google AppEngine (Java one) as a back-end. The problem is that GAE provides only web-based forms for ...

sorl.thumbnail : thumbnail is not a valid tag library?

I am trying to install sorl.thumbnail but am getting the following error message: thumbnail is not a valid tag library: Could not load template library from django.templatetags.thumbnail, No module ...

热门标签