Skip to main content
 首页 » 编程设计

python之在 Pyramid 框架中实现 Sqlalchemy 烧杯缓存

2025年05月04日13langtianya

根据 sqlalchemy 文档提供的缓存 sqlalchemy 查询的示例,我们应该这样做

from caching_query import FromCache 
 
# load Person objects.  cache the result under the namespace "all_people". 
print "loading people...." 
people = Session.query(Person).options(FromCache("default", "all_people")).all() 

我在 development.ini 中对烧杯进行了以下配置

cache.regions = day, hour, minute, second 
cache.type = file 
cache.data_dir = %(here)s/cache/sess/data 
cache.lock_dir = %(here)s/cache/sess/lock 
cache.second.expire = 1 
cache.minute.expire = 60 
cache.hour.expire = 3600 
cache.day.expire = 86400 

当我在我的应用程序中使用上面的示例代码时,数据没有缓存在缓存文件夹中,所以我假设基于内存的缓存是默认的,是否可以将 sqlalchemy 缓存类型切换为基于文件?还是我理解错了?

请您参考如下方法:

您的问题缺少一些细节,但让我试试:

  • 传递给 FromCache() 的第一个参数是 Beaker 缓存区域的名称,它应该与配置的区域之一匹配,但这里不是这种情况。或者您可能在代码中配置了 default 区域(如果区域未知,我希望抛出 BeakerException)?

  • 您需要安装 pyramid_beaker 模块并将其包含在 Pyramid 的项目配置中。我建议你关注 pyramid_beaker manual's Setup section .

  • 为了将 .ini 文件设置传播到 Beaker,您需要在应用程序的 __init__.py 中添加一些额外的代码。这在 Beaker cache region support 中有描述。手册部分。

这是我当前项目的一个工作示例,配置了基于 Beaker 的 session 和缓存(删除了所有不相关的部分):

from pyramid.config import Configurator 
from pyramid_beaker import set_cache_regions_from_settings 
from pyramid_beaker import session_factory_from_settings 
 
def main(global_config, **settings): 
    # Configure Beaker caching/sessions     
    set_cache_regions_from_settings(settings) 
    session_factory = session_factory_from_settings(settings) 
 
    config = Configurator(settings=settings) 
    config.set_session_factory(session_factory) 
    config.include('pyramid_beaker') 
 
    config.add_static_view('static', 'static', cache_max_age=3600) 
    config.add_route('home', '/') 
 
    config.scan() 
    return config.make_wsgi_app()