gpt4 book ai didi

python - SQLAlchemy:如何将作用域 session 绑定(bind)到请求

转载 作者:行者123 更新时间:2023-12-05 04:12:28 40 4
gpt4 key购买 nike

我是 sqlalchemy 的新手,似乎我仍然错过了几个基本概念。我想使用 sqlalchemy 来处理多线程 Web 应用程序中的数据库交互。

所以我开始

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine('mysql://mydb')
session_factory = sessionmaker( autocommit = False,
autoflush = False,
bind = engine )
Session = scoped_session(session_factory)

我使用 MoinMoin wiki 来处理请求,所以我有一个包含请求的对象 macro.request

我现在在某个类中有一个方法,比如说

def do_sth():
session = Session()
# use the session to get some data from the db

Where and how do I tell the Session object which request it is linked to?

阅读 Multi-threaded use of SQLAlchemy , 它说

The ScopedSession object by default uses [threading.local()] as storage, so that a single Session is maintained for all who call upon the ScopedSession registry, but only within the scope of a single thread. Callers who call upon the registry in a different thread get a Session instance that is local to that other thread.

因此“在不同线程中调用注册表的调用者将获得一个对于该其他线程来说是本地的 Session 实例。”

How is a Session instance local if I never told it which request it is linked to?

最佳答案

SQLAlchemy documentation

So our above example of scoped_session usage, where the same Session object is maintained across multiple calls, suggests that some process needs to be in place such that mutltiple calls across many threads don’t actually get a handle to the same session. We call this notion thread local storage, which means, a special object is used that will maintain a distinct object per each application thread. Python provides this via the threading.local() construct.

所以即使我还没有弄清楚如何从给定的 session 中获取当前线程的pidthreading 模块用于将 session 链接到线程。特别是,可以检查 session 的 hash key

session.hash_key

在问题的示例中测试 Session() 在两个调用中提供相同的 session ,当且仅当两者都在同一线程中进行时。

总而言之,只要每个请求都由其自己的线程处理, session 就会正确链接到请求。

关于python - SQLAlchemy:如何将作用域 session 绑定(bind)到请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40328867/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com