1

我注意到app.handle_exception当异常发生时似乎没有被调用app.test_request_context

from flask import *

app = Flask(__name__)
app.handle_exception = lambda e: 'exception!'

@app.route('/foo')
def foo():
    x = 1 / 0
    return 'ok'

if __name__ == '__main__':
    #app.run(port=81) # handle_exception works here
    with app.test_request_context('/foo'):
        print app.dispatch_request() # but not here

这是预期的行为吗?

4

2 回答 2

1

您可以轻松地覆盖此行为并使用相同的处理程序强制处理异常。

def run_test(path=None,check_func=None,*args,**kwargs):
    with app.test_request_context(path,*args,**kwargs):
        try:
            data=app.dispatch_request() 
            if check_func is not None:
                 check_func()
            else:
                print data
        except Exception as e:
            print app.handle_exception(e)

run_test('/')
run_test('/other')

def current_test(data):
     assert 'has some content' in data
run_test('/should_be_checked',check_func=current_test)

还有一句话。

您的方法不起作用,因为您只是不使用 Flask 的那部分,它实际上捕获了异常。您正在直接调用上下文。

从文档中引用:

如果你研究一下 Flask WSGI 应用程序的内部工作原理,你会发现一段代码看起来很像这样:

def wsgi_app(self, environ):
    with self.request_context(environ):
        try:
            response = self.full_dispatch_request()
        except Exception, e:
            response = self.make_response(self.handle_exception(e))
        return response(environ, start_response)

但!以下是正确的方法,因为每个级别的所有 Flask 方法都将以适当的方式调用:

with app.test_request_context():
    with app.test_client() as client:
        resp = client.get('/')
        #and if you need content of response: print resp.data

---

于 2013-03-29T14:16:55.653 回答
1

不确定这是否是您所追求的:根据dispatch_request 的文档

请求调度。匹配 URL 并返回视图或错误处理程序的返回值。这不必是响应对象。为了将返回值转换为正确的响应对象,请调用 make_response()。

在 0.7 版更改:这不再进行异常处理,此代码已移至新的 full_dispatch_request()。

所以,也许换...

with app.test_request_context('/foo'):
    print app.dispatch_request() # but not here

...和...

with app.test_request_context('/foo'):
    print app.full_dispatch_request() # Hopefully this works now :)
于 2013-03-29T15:28:50.683 回答