gpt4 book ai didi

sqlalchemy - Flask + SQLAlchemy [确定提交成功]

转载 作者:行者123 更新时间:2023-12-03 15:51:02 26 4
gpt4 key购买 nike

我在 flask 中有一个 View ,当来自 POST 请求的对象成功提交时,我想用它来显示成功。

在 Controller 中,我有

us = User(data_that_is_not_valid)
db_session.add(us)
db_session.commit()

截至目前,当对象无法提交时,db_commit() 会抛出异常。有没有更友好的方式,只返回 true 或 false 来指定对象是否已添加到数据库中而不抛出错误?

编辑:添加了异常(exception)的副本
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 719, in commit
self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 350, in commit
self._assert_active(prepared_ok=True)
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.8.0-py2.7-linux-x86_64.egg/sqlalchemy/orm/session.py", line 192, in _assert_active
% self._rollback_exception
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (IntegrityError) column email is not unique u'INSERT INTO users (name, email, password) VALUES (?, ?, ?)' ('test', 'test@test.com', 'test')

最佳答案

无论如何都应该准备好您的数据。但这种情况不是数据格式的情况
异常总是好的,你只需要捕获并使用它们

您应该将异常视为返回 False,还应该记录失败的原因,以便以后解决问题

failed=False
try:
db_session.commit()
except Exception as e:
#log your exception in the way you want -> log to file, log as error with default logging, send by email. It's upon you
db_session.rollback()
db_session.flush() # for resetting non-commited .add()
failed=True
#some use of failed var, specific for your case if you need it

为了更好地理解异常: Exceptions python docs
至于你的特定异常看起来像 autocommit 是你的问题。或者没有提交一些以前的 SQL 操作: Sqlalchemy docs

关于sqlalchemy - Flask + SQLAlchemy [确定提交成功],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16331875/

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