添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

了解SQLAlchemy中的session.merge()

1 人关注

I'm trying to understand how to pass SQLAlchemy objects between different threads, and if it's possible at all. Here's a sample code where I try to read an object in one thread and then use it inside another. Why I'm getting 'Instance <User at 0x19fe1c8c088> is not bound to a Session; attribute refresh operation cannot proceed' error? Is it not the right way of using Session.merge()? Error happens at line print('Got user', user.id)

from concurrent.futures import ThreadPoolExecutor
import queue
def read_user(name, queue):
    with Session() as session:
        with session.begin():
            print(f'Reading user with name={name} from DB')
            user = session.query(User).filter_by(name=name).first()
            print('User', user)
            queue.put(user)
def update_user(age, queue):
    user = queue.get()
    print('Got user', user.id)
    with Session() as session:
        with session.begin():
            local_user = session.merge(user)
            print(f'Thread-local user object: {local_user}')
queue = queue.Queue(1)
with ThreadPoolExecutor(max_workers=2) as executor:
    executor.submit(read_user, 'John', queue)