pandas.read_sql 使用 SQLAlchemy 未提交读取

Sam*_*Sam 3 python sqlalchemy isolation-level python-3.x pandas

我正在尝试使用 pandas 函数pd.read_sql读取flush在 SQLAlchemy 会话中创建、添加和编辑但未提交的记录。所以我想在 SQLAlchemy 会话中创建一个对象并在调用commit. 使用 Pandas 0.22.0 和 SQLAlchemy 1.1.10。

我已经尝试将isolation_leveloncreate_engine和其他各种将隔离级别设置为“READ UNCOMMITTED”的方法,但这似乎不起作用。下面的最小示例:

# Import packages 

import pandas as pd
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker

# Set up an example ORM

Base = declarative_base()
class Record(Base):
    __tablename__ = 'records'
    id = Column(Integer, primary_key=True)
    foo = Column(String(255))

# Create a session and engine:

database='foobar'
user=''
password = ''
host = 'localhost'
port = '5432'

connection_string = f"postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}"
engine = create_engine(connection_string, encoding = 'utf8', convert_unicode = True,
    isolation_level='READ_UNCOMMITTED'
)
session = sessionmaker()
session.configure(bind=engine)
db = session()

# Set up the example record:

Record.__table__.create(bind=engine)
record = Record(foo='bar')
db.add(record)
db.flush()

# Attempt to query:

records = pd.read_sql('select * from records', db.get_bind())
assert records.empty
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种解决方案,该解决方案将导致上述代码AssertionError在最后一行抛出一个。records.empty当前评估为真。

Sam*_*Sam 5

当然,我一在这里发帖就明白了。对于后代:使用db.connection()而不是db.get_bind().