pandas.read_sql 使用 SQLAlchemy 读取未提交

pandas.read_sql Read uncommitted with SQLAlchemy

我正在尝试使用 pandas 函数 pd.read_sql 读取已在 SQLAlchemy 会话中创建、添加和 flushed 但未提交的记录。所以我想在 SQLAlchemy 会话中创建一个对象,并在调用 commit 之前用 pandas 查询它。使用 pandas 0.22.0 和 SQLAlchemy 1.1.10.

我已经尝试在 create_engine 上设置 isolation_level,以及将隔离级别设置为 '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

我正在寻找一种解决方案,使上述代码在最后一行抛出 AssertionErrorrecords.empty 当前评估为真。

当然,我一post 就弄明白了。对于 posterity:使用 db.connection() 而不是 db.get_bind()