gpt4 book ai didi

python - Flask handle_exception 不适用于 test_request_context

转载 作者:行者123 更新时间:2023-12-01 05:47:07 26 4
gpt4 key购买 nike

我注意到,当 app.test_request_context 发生异常时,app.handle_exception 似乎不会被调用:

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

这是预期的行为吗?

最佳答案

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

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 的那部分,它实际上捕获了异常。您正在直接调用上下文。

引用文档:

If you look into how the Flask WSGI application internally works, you will find a piece of code that looks very much like this:

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

---

关于python - Flask handle_exception 不适用于 test_request_context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15704680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com