使用搁架模块给了我一些令人惊讶的行为。 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']

有没有人遇到过这个问题,并且是否有解决方法,而不知道所有可能的缓存键 先验?

有帮助吗?

解决方案

根据 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']

因此,答案不是存储任何大的东西,例如RAW XML,而是架子中计算的结果。

其他提示

看到你的例子,我的第一个想法是 cache.has_key() 具有副作用,即此调用将为缓存添加键。你得到什么

print cache.has_key('xxx')
print list(cache.keys())
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top