Python AttributeError:_退出_当使用`with`语句时
我随后为SQLAlchemy编写了一个Python AttributeError:_退出_当使用`with`语句时,python,exception,sqlalchemy,yield,with-statement,Python,Exception,Sqlalchemy,Yield,With Statement,我随后为SQLAlchemy编写了一个session\u scope。当我运行代码时,我得到一个AttributeError异常: Traceback (most recent call last): File "/Users/tuanchauict/workspace/opla-manga/python-server-non-django/demo.py", line 56, in <module> with session_scope() as s: Attribut
session\u scope
。当我运行代码时,我得到一个AttributeError
异常:
Traceback (most recent call last):
File "/Users/tuanchauict/workspace/opla-manga/python-server-non-django/demo.py", line 56, in <module>
with session_scope() as s:
AttributeError: __exit__
回溯(最近一次呼叫最后一次):
文件“/Users/tuanchauict/workspace/opla manga/python server non-django/demo.py”,第56行,在
将会话_scope()作为s:
AttributeError:\uuu退出__
我的代码是:
Session = sessionmaker(bind=engine, autocommit=False, autoflush=False)
def session_scope():
session = Session()
try:
yield session
session.commit()
except Exception as e:
session.rollback()
finally:
session.close()
with session_scope() as session: # <=== error here
pass
Session=sessionmaker(bind=engine,autocommit=False,autoflush=False)
def会话_作用域():
会话=会话()
尝试:
收益期
session.commit()
例外情况除外,如e:
会话。回滚()
最后:
session.close()
使用session_scope()作为session:#您忘记将@contextmanager
装饰器放在函数上(如该页上的代码所示)。我明白了。多谢各位