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

标签 python session sqlalchemy

我是 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/

相关文章:

python - Matplotlib:脚本等待 `input()` 时无法操作绘图

python - speech_recognition 模块卡在 "say something"- python

ruby - Sinatra 中的 session : Used to Pass Variable

security - session cookie 应该始终是 HttpOnly 吗?

python - 在 Python PyQt 桌面应用程序中安全地验证和授权用户

python - 如何为 Github 更新 httplib2 的 cacerts.txt?

python - 画出 turtle python 的形状

asp.net - session 固定 - 表单例份验证

python - 在 sqlalchemy 的 having 子句中使用标签

Python SqlAlchemy + MySql 通过 JSON 列数据过滤