Madawar
Madawar

Reputation: 507

Implementing Sqlalchemy beaker caching in pyramid framework

As per the example provided by sqlalchemy documentation to cache a sqlalchemy query we are suppose to do this

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()

I have the following configuration for beaker in 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

When i use the above example code in my application data is not cached in the cache folder, so i am assuming memory based caching is the default, Is it possible to switch sqlalchemy cache type to file based? or am i getting it wrong?

Upvotes: 2

Views: 918

Answers (1)

Code Painters
Code Painters

Reputation: 7275

Your question is missing some details, but let me try:

  • the first parameter passed to FromCache() is a name of a Beaker cache region, it should match one of the configured regions, which is not the case here. Or perhaps you configure default region in the code (I'd expect BeakerException being thrown if region is unknown)?

  • you need pyramid_beaker module installed and included in Pyramid's project configuration. I suggest you follow pyramid_beaker manual's Setup section.

  • you need some extra code in __init__.py of your application in order to propagate .ini file settings to Beaker. This is described in Beaker cache region support section of the manual.

And here's a working sample from my current project, configuring both Beaker-based sessions and caching (all irrelevant parts removed):

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()

Upvotes: 1

Related Questions