File cache for images

Fredrik Lundh fredrik at pythonware.com
Mon Sep 20 08:04:34 CEST 2004


"me at here.there.nowhere" wrote:
> I'm looking for a way to cache some modified images as files (in a python
> program ofcourse). The scenario would look like this:
>
> getmodifiedimage(filename):
>   is it in cache?
>    is the cache up to date (not older than file)
>    if not, modify filename and store in cache
>      (keyed by filename + modification)
>  return modified image
>
> I'm looking for prior-art before inventing it myself :)

I'm not sure what "modify filename" means, but a straightforward
solution is not that much longer than your pseudocode:

def getmodifiedimage(filename, cache={}):
    try:
        image, mtime = cache[filename]
        if mtime < os.path.getmtime(filename):
            raise KeyError
    except KeyError:
        image = open(filename, "rb").read() # or something
        cache[filename] = image, os.path.getmtime(filename)
    return image

</F> 






More information about the Python-list mailing list