最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Confused with scoped_session, async_scoped_session from SQLAlchemy - Stack Overflow

programmeradmin1浏览0评论

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"))
  sessionmit() # 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

发布评论

评论列表(0)

  1. 暂无评论