如何全局初始化 SQL Alchemy 引擎、会话和 table

How to initialize SQL Alchemy engine, session and table globally

我正在开发一个 python 应用程序,它的大部分功能将与 MySQL 数据库中的特定 table 交互(创建、读取、更新和删除)。我知道我可以使用以下代码查询这个特定的 table:

engine = create_engine(
            f"mysql+pymysql://{username}:{password}@{host}:{port}",
            pool_pre_ping=True
        )
meta = MetaData(engine)
my_table = Table(
    'my_table',
     meta,
     autoload=True,
     schema=db_name
)
dbsession = sessionmaker(bind=engine)
session = dbsession()

# example query to table
results = session.query(my_table).filter(my_table.columns.id >=1)
results.all()

但是,我不明白如何使这些定义(引擎、元、table、会话)对我的所有函数都是全局的。我应该在 init.py 中定义这些东西,然后将它们作为函数参数传递吗?我应该定义一个大 class 并在 class 初始化期间初始化它们吗?

我的目标是能够随时在我的任何函数中查询 table,而不必担心连接是否断开。根据 SQL Alchemy docs:

Just one time, somewhere in your application’s global scope. It should be looked upon as part of your application’s configuration. If your application has three .py files in a package, you could, for example, place the sessionmaker line in your init.py file; from that point on your other modules say “from mypackage import Session”. That way, everyone else just uses Session(), and the configuration of that session is controlled by that central point.

好的,但是 enginetablemeta 呢?我需要担心这些吗?

如果您使用的是单个 table,那么反射的 table 实例 (my_table) 和引擎应该是您需要全局公开的全部内容。

  • 查询不需要元数据对象 (meta),但在需要时可作为 my_table.metadata 使用
  • 会话不是必需的,因为您似乎没有使用 SQLAlchemy ORM。

该引擎维护着一个连接池,您可以查看这些连接以进行 运行 查询(不过不要忘记关闭它们)。此示例代码使用上下文管理器来确保提交事务并关闭连接:

# Check out a connection
with engine.connect() as conn:
    # Start a transaction
    with conn.begin():
        q = select(my_table).where(my_table.c.id >= 1)
        result = conn.execute(q)