1
我是新手使用SQLAlchemy的,我工作的一個複雜的ETL過程,所以我做了下面的簡化代碼:處理跨多個模塊scoped_session與SQLAlchemy的
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
內創建一個數據庫會話。我的問題是,如何在不通過param將會話傳遞給每個方法的情況下,爲module1和module2中的每個worker使用同一個會話?我應該在每個模塊/文件中添加以下行嗎?
engine = create_engine(connection_string, echo=True)
Session = scoped_session(sessionmaker(bind=engine))
session = Session()
你好@univerio,謝謝你的支持。我會嘗試,但你有更好的方法來暗示我嗎?我真的會讚歎它 –
@ Overflow012不知道你在問什麼。這是標準方法。這不適合你嗎? – univerio