使用SQLAlChemy会话作为上下文管理器时,接收"属性错误:__Enter__&Quot;

Receiving quot;AttributeError: __enter__quot; when using SQLAlchemy Session as context manager(使用SQLAlChemy会话作为上下文管理器时,接收quot;属性错误:__Enter__Quot;)

本文介绍了使用SQLAlChemy会话作为上下文管理器时,接收"属性错误:__Enter__&Quot;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到带有以下内容的AttributeError: __enter__。这与with Session(engine) as session相关:

from sqlalchemy import create_engine
from sqlalchemy import text
from sqlalchemy.orm import Session
from sqlalchemy import MetaData
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy import ForeignKey

engine = create_engine("sqlite+pysqlite:///:memory:", echo=True)

with engine.connect() as conn:
    conn.execute(text("CREATE TABLE some_table (x int, y int)"))
    conn.execute(text("INSERT INTO some_table (x, y) VALUES (:x, :y)"),[{"x": 1, "y": 1}, {"x": 2, "y": 4}])

with engine.begin() as conn:
    conn.execute(text("INSERT INTO some_table (x, y) VALUES (:x, :y)"),[{"x": 6, "y": 8}, {"x": 9, "y": 10},
    {"x": 11, "y": 12}, {"x": 13, "y": 14}])

with engine.connect() as conn:
    result = conn.execute(text("Select x,y From some_table"))
    for x, y in result:
        print(f"x:{x} y:{y}")

stmt = text("SELECT x, y FROM some_table WHERE y > :y ORDER BY x, y").bindparams(y=6)

with Session(engine) as session:
    result = session.execute(stmt)
    for row in result:
        print(f'x: {row.x}  y: {row.y}')

我使用的是蟒蛇1.3.23附带的SQLAlChemy版本。

推荐答案

通过上下文管理器运行会话构建/关闭进程,如下所示:

engine = create_engine(...)
Session = sessionmaker(bind=engine)

with Session() as session:
    session.add(something)
    session.commit()

在SQLAlChemy<;1.4上不受支持。

如果您的SQLAlChemy版本为例如1.3.x,则应改为:

engine = create_engine(...)
Session = sessionmaker(bind=engine)

session = Session()
session.add(something)
session.commit()

如果您确实想使用上下文管理器,同时又需要使用SQLAlChemy<;1.4,您可以使用以下方法(复制自SQLAlchemy docs):

### another way (but again *not the only way*) to do it ###

from contextlib import contextmanager

@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()


def run_my_program():
    with session_scope() as session:
        ThingOne().go(session)
        ThingTwo().go(session)

这篇关于使用SQLAlChemy会话作为上下文管理器时,接收&quot;属性错误:__Enter__&Quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用SQLAlChemy会话作为上下文管理器时,接收&quot;属性错误:__Enter__&Quot;

基础教程推荐