“设置会话"在SQLAlchemy会话对象中 [英] "set session" in a SQLAlchemy session object

查看:95
本文介绍了“设置会话"在SQLAlchemy会话对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中使用SQLAlchemy,出于性能原因,需要能够为一个特定的调用指定会话变量/设置:

I'm using SQLAlchemy for a project, and need to be able to specify a session variable/setting for one specific call for performance reasons:

set session max_heap_table_size = 1024 * 1024 * 64;

我当然可以直接在MySQL中(在Shell上)执行此操作,但是如何在SQLAlchemy会话中设置此会话变量?

I can of course do this in MySQL directly (on the shell), but how do I set this session variable in a SQLAlchemy session?

推荐答案

使用

Use a session event to execute an arbitrary SQL statement on each new transaction. You can also use events on the connection level, it depends on your use case.

这是我在会话级别上要做的事情:

Here is how I would do it on the session level:

Session = sessionmaker()
@event.listens_for(Session, 'before_flush')
def set_max_heap_table_size(session, transaction, connection):
    session.execute('SET max_heap_table_size = 1024 * 1024 * 64')

如果不确定哪种方法适合您,只需尝试一下,编写一些测试用例,然后找出是否适合您.

If you are unsure which way works for you, just try them, write some test cases and find out if that works for you.

可能有一个警告(不确定):由于连接没有断开而是返回到池中,因此该设置可能会持续存在.在这种情况下,您可能还需要附加一些内容以恢复默认设置,例如在after_flush事件上.对于这一点,我不太确定,您可能想尝试一下.如果不需要这样做,也可以使用after_begin事件,但是没有真正的before_close事件可以包装它,因此可能会引起问题.

There may be one caveat (unsure): Since the connection is not dropped but returned to the pool, the setting might persist. In this case you might also want to attach something to restore the default, e.g. on the after_flush event. I am not entirely sure on this one, you might want to experiment. If this is unnecessary, you could also use the after_begin event, but there is no real before_close event that wraps it, so it could create issues.

这篇关于“设置会话"在SQLAlchemy会话对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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