2

シェルフモジュールを使用すると、驚くべき動作が得られます。keys()、iter()、およびiteritems()は、シェルフ内のすべてのエントリを返すわけではありません。コードは次のとおりです。

cache = shelve.open('my.cache')
# ...
cache[url] = (datetime.datetime.today(), value)

後で:

cache = shelve.open('my.cache')
urls = ['accounts_with_transactions.xml', 'targets.xml', 'profile.xml']
try:
    print list(cache.keys()) # doesn't return all the keys!
    print [url for url in urls if cache.has_key(url)]
    print list(cache.keys())
finally:
    cache.close()

出力は次のとおりです。

['targets.xml']
['accounts_with_transactions.xml', 'targets.xml']
['targets.xml', 'accounts_with_transactions.xml']

誰かが以前にこれに遭遇したことがありますか、そしてすべての可能なキャッシュキーを事前に知らなくても回避策はありますか?

4

2 に答える 2

3

Pythonライブラリリファレンスによると:

...データベースは、(残念ながら) dbm を使用する場合、その制限の対象にもなります — これは、データベースに格納されているオブジェクト (のピクルされた表現) がかなり小さくなければならないことを意味します...

これは「バグ」を正しく再現します。

import shelve

a = 'trxns.xml'
b = 'foobar.xml'
c = 'profile.xml'

urls = [a, b, c]
cache = shelve.open('my.cache', 'c')

try:
    cache[a] = a*1000
    cache[b] = b*10000
finally:
    cache.close()


cache = shelve.open('my.cache', 'c')

try:
    print cache.keys()
    print [url for url in urls if cache.has_key(url)]
    print cache.keys()
finally:
    cache.close()

出力で:

[]
['trxns.xml', 'foobar.xml']
['foobar.xml', 'trxns.xml']

したがって、答えは生の xml のような大きなものは保存せず、シェルフに計算結果を保存することです。

于 2009-08-25T08:34:06.993 に答える
0

あなたの例を見て、私の最初の考えはcache.has_key()副作用があるということです。つまり、この呼び出しはキャッシュにキーを追加します。あなたは何のために得ますか

print cache.has_key('xxx')
print list(cache.keys())
于 2009-08-25T07:48:15.963 に答える