使用 SQLAlchemy 跨多个模块处理 scoped_session

Handling scoped_session across multiple modules with SQLAlchemy

我是使用 SQLAlchemy 的新手,我正在处理一个复杂的 ETL 过程,所以我做了以下简化代码:

module1.py

class Foo:
    def foo_method(self):
        # doing stuff with database

module2.py

class Bar:
    def bar_method(self):
        # doing stuff with database

main_script.py

from module1 import Foo
from module2 import Bar

def run():
    with Pool(processes = num_workers) as pool:
        responses = [pool.apply_async(some_func, (param)) for param in params]
        for response in responses:
            response.get()


def some_func(param):
    engine = create_engine(connection_string, echo=True)
    Session = scoped_session(sessionmaker(bind=engine))
    session = Session()    
    # Start doing some stuff with database
    foo = Foo()
    foo.foo_method()

    bar = Bar()
    bar.bar_method()

所以我有一个带工作进程的池。当我调用 main_script.run() 时,每个工作人员都会在 some_func 中创建一个数据库会话。我的问题是如何在不通过参数将会话传递给每个方法的情况下,为 module1 和 module2 中的每个工作人员使用相同的会话?我应该在每个 module/file 中添加以下行吗?

    engine = create_engine(connection_string, echo=True)
    Session = scoped_session(sessionmaker(bind=engine))
    session = Session()   

scoped_session 应该在模块级别创建。对于您的项目结构,这可能意味着有一个单独的模块来容纳引擎和会话:

db.py

engine = create_engine(connection_string, echo=True)
Session = scoped_session(sessionmaker(bind=engine))

module1.py

from db import Session

class Foo:
    def foo_method(self):
        session = Session()
        session.query(...)...