python - Flask源码异常处理问题
阿神
阿神 2017-04-18 10:19:57
0
1
940

Flask version: 0.3

我事先在views.py里面定义了如下的异常处理方法:

@app.errorhandler(404)
def page_not_found():
    return "this page is not found.", 404
    

@app.errorhandler(500)
def page_error():
    return "this page is error.", 500
    
#:: 这两个异常处理方法都是错误的,因为没有加参数。

先贴几段源码

#:: 片段1
def wsgi_app(self, environ, start_response):
    with self.request_context(environ):
        try:
            rv = self.preprocess_request()
            if rv is None:
                rv = self.dispatch_request()
            response = self.make_response(rv)
            response = self.process_response(response)
        except Exception, e:
            response = self.make_response(self.handle_exception(e))
        return response(environ, start_response)
        

#:: 片段2
def dispatch_request(self):
    req = _request_ctx_stack.top.request
    try:
        if req.routing_exception is not None:
            raise req.routing_exception  #:: 抛出异常
        return self.view_functions[req.endpoint](**req.view_args)
    except HTTPException, e:
        return self.handle_http_exception(e)


#:: 片段3
class _RequestContext(object):
    def __init__(self, app, environ):
        self.app = app
        self.url_adapter = app.url_map.bind_to_environ(environ)
        self.request = app.request_class(environ)
        self.session = app.open_session(self.request)
        if self.session is None:
            self.session = _NullSession()
        self.g = _RequestGlobals()
        self.flashes = None

        try:
            self.request.endpoint, self.request.view_args = \
                self.url_adapter.match()  #:: 不匹配
        except HTTPException, e:
            print e.code, e.description
            self.request.routing_exception = e
            

#:: 片段4
def handle_exception(self, e):
    handler = self.error_handlers.get(500)
    if self.debug:
        raise
    self.logger.error("hello")
    self.logger.exception('Exception on %s [%s]' % (
        request.path,
        request.method
    ))

    if handler is None:
        return InternalServerError()
    return handler(e) #:: handler不为None,之前定义了500的错误处理

然后我在浏览器输入了一个不存在的路由http://localhost:5000/test,想看Flask如何异常处理。

请求过来之后会先执行片段1, 然后代码走到片段3请求上下文,片段3self.url_adapter.match()抛出HTTPException异常被捕获。然后执行到片段2,然后抛出异常被片段1捕获到执行片段4,最后会执行到handler(e)这条语句。

我的问题来了,因为我定义的500的错误处理里面,没有加参数,导致这条语句执行失败。

报了如下错误:

Traceback (most recent call last):
  File "/Users/virtualenvs/full-stack/lib/python2.7/site-packages/werkzeug/serving.py", line 180, in run_wsgi
    execute(self.server.app)
  File "/Users/virtualenvs/full-stack/lib/python2.7/site-packages/werkzeug/serving.py", line 168, in execute
    application_iter = app(environ, start_response)
  File "/Users/virtualenvs/full-stack/flask0.3/examples/flaskr/flask.py", line 1435, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/virtualenvs/full-stack/lib/python2.7/site-packages/werkzeug/wsgi.py", line 591, in __call__
    return self.app(environ, start_response)
  File "/Users/virtualenvs/full-stack/flask0.3/examples/flaskr/flask.py", line 1382, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/virtualenvs/full-stack/flask0.3/examples/flaskr/flask.py", line 1266, in handle_exception
    return handler(e)
TypeError: page_error() takes no arguments (1 given)

Traceback当中能看出最后也是这句的错误。然而浏览器还是返回了500的页面,返回的内容是Werkzeug自定义的页面内容。

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

既然程序都已经执行错误了,那为什么还能够返回HTTP Response呢?
谢谢:-)

阿神
阿神

闭关修行中......

모든 응답(1)
黄舟

오류 메시지는 매우 명확합니다
파일 "/Users/virtualenvs/full-stack/flask0.3/examples/flaskr/flask.py", line 1266, in handler_Exception

으아아아

TypeError: page_error()는 인수를 사용하지 않습니다(1개 제공)

page_error()는 매개변수를 사용하지 않으며 매개변수를 전달합니다.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿