【问题标题】:Handling scoped_session across multiple modules with SQLAlchemy使用 SQLAlchemy 跨多个模块处理 scoped_session
【发布时间】:2017-05-03 20:22:33
【问题描述】:

我是使用 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

ma​​in_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 内创建一个数据库会话。我的问题是如何在不通过参数将会话传递给每个方法的情况下为模块 1 和模块 2 中的每个工作人员使用相同的会话?我应该在每个模块/文件中添加以下行吗?

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

【问题讨论】:

    标签: python python-3.x sqlalchemy python-multiprocessing


    【解决方案1】:

    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(...)...
    

    【讨论】:

    • 您好@univerio,感谢您的回答。我会试试看,但你有更好的方法来建议我吗?我真的很感激它
    • @Overflow012 不知道你在问什么。这是标准方法。这不适合你吗?
    • 如何使用这种方法运行单元测试(使用内存数据库)?
    • @Ali 他们也不例外。如果你在测试环境中,你只需要有条件地构造一个不同的引擎。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2013-11-09
    • 2011-07-29
    • 2015-04-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多