2008-10-15 108 views
21

是否SQLAlchemy的支持某种类型的缓存,所以如果我反复运行,将会返回从缓存中,而不是查询数据库的响应相同的查询?当数据库更新时,该缓存是否自动清除?SQLAlchemy是否支持缓存?

或者在CherryPy + SQLAlchemy安装程序上实现此目的的最佳方法是什么?

回答

41

我们有一个非常全面的缓存解决方案,结合嵌入式挂钩为例,在0.6 。这是一个配置子类查询,让它知道Beaker的方法,并允许通过查询选项控制显式查询的查询缓存以及懒惰加载器。

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

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

14

不回答你的第二个问题,但在这个环节上的评论表明,SQLAlchemy的不支持cacheing: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 

Jonathan Ellis说...

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. 
+2

此链接http://www.mail-archive.com/[email protected]/msg15667.html提示/显示,后续查询不使用查询,但从身份映射返回实例,但这仅适用于使用主键查询的情况。 – andho 2009-10-06 16:38:57

-4

不,但您可以使用memcache进行缓存。

3

的SQLAlchemy支持两种类型的缓存:

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

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

  2. 缓存query对象,以便Python解释器不必手动每次重新组装的查询字符串。这些查询被称为baked queries和高速缓存被称为baked。基本上它会缓存所有的动作sqlalchemy在进入数据库之前 - 它不会减少数据库调用。最初的基准测试显示,代码冗长度稍微增加的代价在query世代时间内加速了40%。

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