Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python AttributeError:_退出_当使用`with`语句时_Python_Exception_Sqlalchemy_Yield_With Statement - Fatal编程技术网

Python AttributeError:_退出_当使用`with`语句时

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

我随后为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:
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
装饰器放在函数上(如该页上的代码所示)。我明白了。多谢各位