9.2 contextmanager
1.contextmanager简单讲解
@contextmanager
def book_mark():
print('《', end='')
yield
print('》', end='')
with book_mark():
print('钢铁',end='')2.结合继承,contextmanager,yield,rollback来简化try-except的数据库事务代码
from flask_sqlalchemy import SQLAlchemy as _SQLAlcmemy
class SQLAlchemy(_SQLAlcmemy):
@contextmanager
def auto_commit(self):
try:
yield
self.session.commit()
except Exception as e:
self.session.rollback()
raise eLast updated
Was this helpful?