SQLAlchemy+Tornado:如何为 SQLAlchemy 的 ScopedSession 创建 scopefunc? [英] SQLAlchemy+Tornado: How to create a scopefunc for SQLAlchemy's ScopedSession?

查看:21
本文介绍了SQLAlchemy+Tornado:如何为 SQLAlchemy 的 ScopedSession 创建 scopefunc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Tornado,我想创建一些中间件魔法,以确保我的 SQLAlchemy 会话正确关闭/清理,以便对象不会从一个请求共享到下一个请求.诀窍在于,由于我的一些龙卷风处理程序是异步的,我不能只为每个请求共享一个会话.

Using tornado, I want to create a bit of middleware magic that ensures that my SQLAlchemy sessions get properly closed/cleaned up so that objects aren't shared from one request to the next. The trick is that, since some of my tornado handlers are asynchronous, I can't just share one session for each request.

所以我要尝试创建一个 ScopedSession,它知道如何为每个请求创建一个新会话.我需要做的就是为我的代码定义一个 scopefunc,它可以将当前正在执行的请求转换为某种唯一键,但是我似乎无法弄清楚如何获取当前请求任何一个时间点(在当前 RequestHandler 的范围之外,我的函数也无权访问).

So I am left trying to create a ScopedSession that knows how to create a new session for each request. All I need to do is define a scopefunc for my code that can turn the currently executing request into a unique key of some sort, however I can't seem to figure out how to get the current request at any one point in time (outside of the scope of the current RequestHandler, which my function doesn't have access to either).

有什么我可以做的事情吗?

Is there something I can do to make this work?

推荐答案

您可能希望将 Session 与请求本身相关联(即,如果不方便,请不要使用 scopedsession).然后你可以说,request.session.仍然需要在开始/结束时使用钩子进行设置/拆卸.

You might want to associate the Session with the request itself (i.e. don't use scopedsession if it's not convenient). Then you can just say, request.session. Still needs to have hooks at the start/end for setup/teardown.

自定义范围功能

def get_current_tornado_request():
   # TODO: ask on the Tornado mailing list how
   # to acquire the request currently being invoked

Session = scoped_session(sessionmaker(), scopefunc=get_current_tornado_request)

这篇关于SQLAlchemy+Tornado:如何为 SQLAlchemy 的 ScopedSession 创建 scopefunc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆