[Python] Actual practical advantage of SQLAlchemy scoped_session vs classic session in worker

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    What is the actual practical advantage of using a scoped_session vs a normal session when using a contextmanager to handle opening and closing of the session at the appropriate times?

    In the following example, the commits close the session before time consuming operations so no issue with connections therefore I don't see the advantage of using a scoped_session. Couldn't find a source using the normal sessions this way (creating them in the worker) so that's why I'm asking here.

    example using normal session

    Session = sessionmaker(autocommit=False, autoflush=False, bind=engine, expire_on_commit=False)
    executor = ThreadPoolExecutor(max_workers=4)

    def worker(input):
    with Session() as db:
    db.add(NewObject(input=input))
    db.commit()
    result = # do long request to external service
    db.add(AnotherNewObject(input=input, result=result))
    db.commit()

    def main():
    with Session() as db:
    for i in range(4):
    db.add(NewInitObject(i=i))
    db.commit()
    executor.submit(worker, i)

    main()


    example using scoped_session (identical as above except for Session object)

    Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine, expire_on_commit=False))
    executor = ThreadPoolExecutor(max_workers=4)

    def worker(input):
    with Session() as db:
    db.add(NewObject(input=input))
    db.commit()
    result = # do long request to external service
    db.add(AnotherNewObject(input=input, result=result))
    db.commit()

    def main():
    with Session() as db:
    for i in range(4):
    db.add(NewInitObject(i=i))
    db.commit()
    executor.submit(worker, i)

    main()

    Continue reading...

Compartilhe esta Página