3.2 Caching

pylastfm provides some simple caching mechanisms. To enable caching you have to update the modules configuration. The simplest way to enable caching is to:

>>> import lastfm
>>> lastfm.config.update({"cache.on", True})

The update function will automatically reload all related modules, including the caching module with the new configuration options.

pylastfm provides two caching backends: The first is an In-Memory-Cache - which is the default, the second one is a filesystem based cache which keeps it's information accross sessions on a per user basis. You can choose between both backends by setting the "cache.backend" option. Here's a complete example:

>>> import lastfm
>>> lastfm.config.update({"cache.on" : True, "cache.backend" : "filesystem"})
>>> artists = lastfm.user.top_artists("RJ")
2007-02-20 12:22:08,280 DEBUG Retrieving 'http://ws.audioscrobbler.com/1.0/user/RJ/profile.xml'
2007-02-20 12:22:08,526 DEBUG Retrieving 'http://ws.audioscrobbler.com/1.0/user/RJ/topartists.xml'
>>> # Let's do it again!
>>> artists = lastfm.user.top_artists("RJ")
2007-02-20 12:22:17,300 DEBUG Retrieving 'http://ws.audioscrobbler.com/1.0/user/RJ/profile.xml'
2007-02-20 12:22:17,301 DEBUG Cached 'http://ws.audioscrobbler.com/1.0/user/RJ/profile.xml'
2007-02-20 12:22:17,302 DEBUG Retrieving 'http://ws.audioscrobbler.com/1.0/user/RJ/topartists.xml'
2007-02-20 12:22:17,302 DEBUG Cached 'http://ws.audioscrobbler.com/1.0/user/RJ/topartists.xml'
>>>

As you can see, calling the top_artists function a second time with the same parameters returns the information from the filesystem cache.

You can easily write your own cache backend by subclassing lastfm.lib.cache.BaseCache and setting the "cache.backend" to an import path (i.e. "mymodule.MyCachingClass"). pylastfm will dynamically import your class and use it as it's caching backend.