我有一个Flask应用程序,其路径如下所示:
from _mysql_exceptions import OperationalError
@mod.route('/', methods=['POST'])
def do_something_route():
try:
do_something(request.form)
except OperationalError:
message = {"error": "something went wrong"}
return jsonify(message, mimetype='application/json'), 400
do_something()
功能:
def do_something(self, form_data):
model = MyModel()
for key in form_data:
if hasattr(model, key):
setattr(model, key, form_data.get(key))
db.session.add(model)
db.session.commit()
return model
当我向do_something_route
发送违反我的数据库约束的垃圾数据时,会引发OperationalError
异常并返回状态代码为500的响应并返回堆栈跟踪,而不是我的jsonified消息状态为400。
当我尝试这是一个普通的旧python shell时,它似乎按预期工作:
>>> from _mysql_exceptions import OperationalError
>>> raise OperationalError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_mysql_exceptions.OperationalError
>>> try:
... raise OperationalError
... except OperationalError:
... print 'test'
...
test
为什么except OperationalError:
没有抓住OperationalError
例外? Flask是否正在做一些早期回复的黑魔法?
答案 0 :(得分:1)
from sqlalchemy.exc import OperationalError
try:
# do something
except OperationalError:
# do something