SQLAlchemy 是不是支持缓存?

Posted

技术标签:

【中文标题】SQLAlchemy 是不是支持缓存?【英文标题】:Does SQLAlchemy support caching?SQLAlchemy 是否支持缓存? 【发布时间】:2010-09-17 07:44:50 【问题描述】:

SQLAlchemy 是否支持某种缓存,所以如果我重复运行相同的查询,它会从缓存返回响应而不是查询数据库? DB更新时这个缓存会自动清空吗?

或者在 CherryPy + SQLAlchemy 设置上实现此功能的最佳方法是什么?

【问题讨论】:

【参考方案1】:

不是第二个问题的答案,但来自此链接中的 cmets 表明 SQLAlchemy 不支持缓存:http://spyced.blogspot.com/2007/01/why-sqlalchemy-impresses-me.html

乌鸦说……

Does SQLAlchemy do any kind of internal caching?

For example, if you ask for the same data twice (or an obvious subset
of the initially requested data) will the database be hit once or twice?

I recently wrote a caching database abstraction layer for an
application and (while fun) it was a fair bit of work to get it to a
minimally functional state. If SQLAlchemy did that I would seriously
consider jumping on the bandwagon.

I've found things in the docs that imply something like this might be
going on, but nothing explicit.
4:36 PM

乔纳森·埃利斯说……

No; the author of SA [rightly, IMO] considers caching a separate concern.

What you saw in the docs is probably the SA identity map, which makes it so 
if you load an instance in  two different places, they will refer
to the same object. But the database will still be queried twice, so it is
not a cache in the sense you mean.

【讨论】:

此链接mail-archive.com/sqlalchemy@googlegroups.com/msg15667.html 建议/显示后续查询不使用查询,而是从身份映射返回实例,但这仅在您使用主键查询时有效。【参考方案2】:

或通过弱引用字典 (weakref.WeakValueDictionary) 使用应用程序级缓存,请参见此处的示例:http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject

【讨论】:

【参考方案3】:

我们有一个非常全面的缓存解决方案,作为一个结合嵌入式钩子的例子,在 0.6 中。这是 Query 的子类化方法,使其了解 Beaker,并允许通过查询选项控制显式查询和惰性加载器的查询缓存。

我现在正在生产中运行它。示例本身位于 dist 中,介绍文档位于 http://www.sqlalchemy.org/docs/orm/examples.html#beaker-caching 。

更新:烧杯现在已替换为 dogpile 缓存:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.dogpile_caching

【讨论】:

【参考方案4】:

SQLAlchemy 支持两种类型的缓存:

    缓存结果集,以便重复运行相同的查询命中缓存而不是数据库。它使用dogpile 支持许多不同的后端,包括memcachedredis 和基本平面文件。

    文档在这里:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.dogpile_caching

    缓存query 对象,这样Python 解释器就不必每次都手动重新组装查询字符串。这些查询称为baked queries,缓存称为baked。基本上,它会缓存sqlalchemy 在访问数据库之前执行的所有操作——它不会减少数据库调用。最初的基准测试表明,在代码冗长程度略有增加的情况下,query 生成时间的速度提高了高达 40%。

    文档在这里:http://docs.sqlalchemy.org/en/latest/orm/extensions/baked.html

【讨论】:

结果集的缓存不使用Identity map吗?在这种情况下,我第一次听说了 dogpile。还是它与身份映射有某种关系?

以上是关于SQLAlchemy 是不是支持缓存?的主要内容,如果未能解决你的问题,请参考以下文章

Flask-SQLAlchemy 学习总结

flask-sqlalchemy的使用

flask_sqlalchemy

SQlAlchemy的增删改查

尝试连接数据库和 Web 容器时 SQLAlchemy 连接被拒绝

如何禁用SQLAlchemy缓存?