[Python] Confused with scoped_session, async_scoped_session from SQLAlchemy

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    Been reading the documentation from SQLAlchemy, and I still can't get it. What are the purpose of scoped_session / async_scoped_session.

    I prefer to use this syntax in my code, and as my understand.

    engine = create_engine(DATABASE_URL, pool_size=1, max_overflow=0)
    Base.metadata.create_all(engine)
    session_maker = sessionmaker(engine, expire_on_commit=False)

    def add_user():
    with session_maker.begin() as session:
    session.add(User(name="John Doe"))



    So if I use this syntax in multi-threading environment, would it be safe. As my understanding, this will create a new Session object (and start a transaction) in each thread. So with this syntax, I can spam Session in my code without even care about thread safe, right?

    My assumption about scoped_session, that I can do something like this.

    engine = create_engine(DATABASE_URL, pool_size=1, max_overflow=0)
    Base.metadata.create_all(engine)
    session_maker = scoped_session(sessionmaker(engine, expire_on_commit=False))
    def add_user():
    session = session_maker()
    session.add(User(name="John Doe"))
    session.commit() # don't have to call close


    Each thread will have the same Session object (maybe also for each request)

    Can someone clarify for me about the usage / purpose of scoped_session (also async_scoped_session), thanks in advance.

    I tried to read documentation and others people code but sill don't get it

    Continue reading...

Compartilhe esta Página