1

None でない場合にのみ、関数の戻り値をキャッシュしようとしています。

次の例では、 someFunction が some-url から 1 時間データを取得できた場合に備えて、 someFunction の結果をキャッシュするのが理にかなっています。

データを取得できなかった場合、結果を 1 時間 (またはそれ以上) キャッシュするのは意味がありませんが、おそらく 5 分間はキャッシュします (したがって、some-domain.com のサーバーが復旧する時間があります)。

def _cachekey(method, self, lang):
    return (lang, time.time() // (60 * 60))

@ram.cache(_cachekey)
def someFunction(self, lang='en'):
    data = urllib2.urlopen('http://some-url.com/data.txt', timeout=10).read()

    except socket.timeout:
        data = None
    except urllib2.URLError:
        data = None

    return expensive_compute(data)

_cachekey を呼び出しmethod(self, lang)てもあまり意味がありません。

4

2 に答える 2

1

このコードはコメントするには長すぎるため、他の人に役立つことを願ってここに投稿します。

#initialize cache
from zope.app.cache import ram
my_cache = ram.RAMCache()
my_cache.update(maxAge=3600, maxEntries=20)
_marker = object()


def _cachekey(lang):
    return (lang, time.time() // (60 * 60))


def someFunction(self, lang='en'):

    cached_result = my_cache.query(_cacheKey(lang), _marker)

    if cached_result is _marker:
        #not found, download, compute and add to cache
        data = urllib2.urlopen('http://some-url.com/data.txt', timeout=10).read()
        except socket.timeout:
            data = None
        except urllib2.URLError:
            data = None

        if data is not None:
            #cache computed value for 1 hr
            computed = expensive_compute(data)
            my_cache.set(data, (lang, time.time() // (60 * 60) )
        else:
            # allow download server to recover 5 minutes instead of trying to download on every page load
            computed = None
            my_cache.set(None, (lang, time.time() // (60 * 5) )

        return computed


    return cached_result
于 2013-09-25T14:06:11.643 に答える