3

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クラスの 404 エラーを処理するにはどうすればよいですか?.get()

編集:

a を呼び出す理由RequestHandlerは、セッション ( request.session) にアクセスするためです。そうしないと、現在のユーザーを 404 エラー ページのテンプレートに渡すことができません。つまり、StackOverflow 404 エラー ページでユーザー名を確認できます。Web サイトの 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)
4

1 に答える 1

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()

ただし、requestで余分な例外引数をこっそりと使用する必要がありますroute_args

于 2012-05-24T11:30:05.700 に答える