[英]What type of Exception should SQLAlchemy model raise when an object is not found in DB?
I have a web-app that uses SQLAlchemy with the Flask framework. 我有一个使用Flask框架使用SQLAlchemy的Web应用程序。
Below is My SQLAlchemy model (simplified): 以下是My SQLAlchemy模型(简化):
class MyModelA(db.Model):
a_id = db.Column(UUIDType(binary=False), nullable=False, primary_key=True)
@classmethod
def get_model_a(cls, a_id):
try:
found_a = cls.query.get(a_id)
except StatementError: # when a_id is not a 16-character string
raise SomeException
else:
if found_a is None:
raise SomeException
Here is the Flask method that implements the HTTP endpoint which lets users query the database with an aID
: 这是Flask方法,它实现HTTP端点,该端点使用户可以使用
aID
查询数据库:
@app.route('/does_a_exist', methods=['post'])
def does_a_exist():
try:
variable_id = request.get_json().get('a_id')
s = len(variable_id) # None object haven't any length
MyModelA.get_model_a(variable_id)
except SomeException:
return jsonify(goodbye='world'), httplib.HTTP_404_NOT_FOUND
else:
return jsonify(hello='world'), httplib.HTTP_200_OK
When the get_model_a()
fails to find the database row with the given a_id
, I want it to raise an exception ( SomeException
) which will be caught by the does_a_exist()
which will respond to the user with a 404
. 当
get_model_a()
未能找到具有给定a_id
的数据库行时,我希望它引发一个异常( SomeException
),该异常将由does_a_exist()
捕获,并以404
响应用户。
My question is: Which Exception class is most suitable to be used in place of SomeException
?? 我的问题是:哪个Exception类最适合用于代替
SomeException
? Can someone recommend one? 有人可以推荐一个吗? I'm a SQLAlchemy newbie but I know Django well.
我是SQLAlchemy的新手,但我对Django很了解。 In Django I would have raised an
ObjectDoesNotExist
Exception. 在Django中,我会引发
ObjectDoesNotExist
异常。 What is the corresponding SQLAlchemy exception I should use here? 我在这里应该使用什么对应的SQLAlchemy异常?
If you do not want to create your own exception class for this error, the sqlalchemy.orm.exc.NoResultFound
should suit your purposes. 如果您不想为此错误创建自己的异常类,则
sqlalchemy.orm.exc.NoResultFound
应该适合您的目的。
The docs describe the exception as: 文档将异常描述为:
A database result was required but none was found.
需要数据库结果,但未找到任何结果。
http://docs.sqlalchemy.org/en/latest/orm/exceptions.html#sqlalchemy.orm.exc.NoResultFound http://docs.sqlalchemy.org/en/latest/orm/exceptions.html#sqlalchemy.orm.exc.NoResultFound
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.