2013-05-02 31 views
2

我有一個瓶頸視圖,當成功提交POST請求中的對象時,我想用它來顯示成功。Flask + SQLAlchemy [確定提交成功]

在控制器中,我有

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

截至目前,db_commit()拋出時該對象不能被提交異常。有一種更友好的方式,只是返回true或false來指定對象是否已添加到數據庫而不會引發錯誤?

編輯:添加例外的副本

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', '[email protected]', 'test') 
+0

它拋出什麼異常? – Blender 2013-05-02 06:47:45

+0

添加了發帖異常。 – user1431282 2013-05-02 07:06:00

+2

爲什麼不在提交數據庫之前檢查電子郵件是否是唯一的? – Blender 2013-05-02 07:07:47

回答

2

你的數據應該反正準備。但是,這種情況下是不是數據格式的情況下
和異常是一件好事,你只需要捕捉和利用它們

你應該考慮的例外是返回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
至於你具體的異常看起來就像是自動提交您的問題。或者沒有提交以前的SQL操作:Sqlalchemy docs