2012-05-24 3 views
3

Google App Engine (Python)에서 webapp2 프레임 워크를 사용하고 있습니다. webapp2 exception handling: exceptions in the WSGI app에서는 함수에서 404 오류를 처리하는 방법을 설명한 것 :webapp2 처리 webapp2 404 대신 requesthandler 클래스 메소드에서 오류가 발생했습니다.

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 오류 페이지의 템플릿에 현재 사용자를 전달할 수 없습니다. 즉 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) 

답변

3

오류 처리기 요청 처리기 callables의 호출 규칙이 다른 :

  • 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에서 추가 예외 인수를 몰래해야합니다.

+0

'Webapp2HandlerAdapter'에서 파생 된'RequestHandler' 클래스의 예제를 제공 할 수 있습니까? 그리고 404 오류를 처리합니까? – Korneel

+0

또한 내 응용 프로그램의 모든 'RequestHandler'는'BaseRequestHandler'에서 파생됩니다. 오류 처리기 클래스는 두 클래스 ('BaseRequestHandler'와'Webapp2HandlerAdapter')에서 파생되어야합니까? – Korneel

+0

'callable = Webapp2HandlerAdapter (handlers.HomeHandler)'를 사용하여 호출 가능 객체의 핸들러를 변환 할 수 있습니다. – proppy

관련 문제