English 中文(简体)
SQLAlchemy支持缓存吗?
原标题:
  • 时间:2008-10-15 14:26:30
  •  标签:

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

或者在CherryPy + SQLAlchemy设置中实现这个的最佳方法是什么?

最佳回答

我们拥有一个相当全面的缓存解决方案,例如与嵌入式钩子一起在0.6中使用。这是一个将查询子类化的配方,使其意识到Beaker,并允许通过查询选项控制查询缓存以及延迟加载器。

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

更新:现在已经用dogpile缓存替换了Beaker:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.dogpile_caching

问题回答

不是对你的第二个问题的答案,但从这个链接中的评论表明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.

SQLAlchemy 支持两种类型的缓存:

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

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

  2. query对象缓存,这样Python解释器不必每次手动重新组装查询字符串。这些查询被称为烘焙查询,缓存被称为。基本上,它缓存了sqlalchemy在访问数据库之前执行的所有操作-它并不减少数据库调用。最初的基准测试显示,在稍微增加代码冗长度的情况下,query生成时间可以加速高达40%。

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

或者使用应用程序级缓存,通过弱引用字典(weakref.WeakValueDictionary)实现,可以查看这里的示例:http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject





相关问题
热门标签