Pet*_*mit 6 python sqlalchemy integrity
我有一个非常简单的SqlAlchemy模型
class User(Base):
""" The SQLAlchemy declarative model class for a User object. """
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
phone = Column(String, unique=True)
email = Column(String, unique=True)
Run Code Online (Sandbox Code Playgroud)
插入新用户时,IntegrityError如果电子邮件或电话是重复的,则可能会发生.
有没有办法检测哪些列违反了完整性错误?或者是进行单独查询以查看或存在值的唯一方法?
小智 9
try:
....
except IntegrityError as e:
print(e.orig.diag.message_detail)
Run Code Online (Sandbox Code Playgroud)
这对我有用。
小智 7
不幸的是,没有干净的方法可以做到这一点,但我在 IntegrityError 和解析模块上使用 orig 属性:
try:
db.session.add(user)
db.session.commit()
except IntegrityError, e:
dupe_field = parse('duplicate key value violates unique constraint "{constraint}"\nDETAIL: Key ({field})=({input}) already exists.\n', str(e.orig))["field"]
Run Code Online (Sandbox Code Playgroud)
这可能不是 IntegrityError 抛出的唯一错误字符串,它可能会在 SQLAlchemy 的未来更新中发生变化,因此它并不理想
小智 5
您可以使用以下方式获取底层代码、消息,并相应地格式化消息。
except exc.IntegrityError as e:
errorInfo = e.orig.args
print(errorInfo[0]) #This will give you error code
print(errorInfo[1]) #This will give you error message
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您必须从 sqlalchemy 导入 exc:from sqlalchemy import exc
如果您需要任何其他信息,请告诉我。我可以试试看
有关 sqlalchemy exc 的更多信息,请查找代码:https : //github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/exc.py
Jac*_*rge -4
我通常为此使用 try catch。
try:
session.commit()
catch:
str(sys.exc_info()[0]) + " \nDESCRIPTION: "+ str(sys.exc_info()[1]) + "\n" + str(sys.exc_info()[2])
Run Code Online (Sandbox Code Playgroud)
当我遇到完整性错误时,我收到以下消息,我会跳过该特定交易并继续其余交易
DESCRIPTION: (IntegrityError) duplicate key value violates unique constraint "test_code"
DETAIL: Key (test_code)=(5342) already exists.
'INSERT INTO test_table (pk, test_code, test_name) VALUES (%(pk)s, %(test_code)s, %(test_name)s)' { 'pk': '1', 'test_code': '5342', 'test_name': 'test' }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1476 次 |
| 最近记录: |