2013-03-18 78 views
1

在SQLAlchemy中,發生異常後,會因爲回滾而需要重新設置。我是否應該在呼叫之間始終設置會話?異常後的SQLAlchemy會話

user = User('username', 'Full Name', 'password', 'email', 
       datetime.now(), 'username') 
session.add(user) 
try: 
    session.commit() 
except SQLAlchemyError: 
    pprint('Not quite right...') 

# the session needs to be re-instantiated in case of an exception. 
# should I always do it or only if there was an exception above? 
session = Session() 
res = session.query(User).all() 
... 

回答

2

魚:

try: 
    session.commit() 
except SQLAlchemyError: 
    pprint('Not quite right...') 
    session.rollback() 

Fishing rod