首页 \ 问答 \ 如何使用klepto在磁盘上使用LRU缓存?(How to use LRU caching on disk with klepto?)

如何使用klepto在磁盘上使用LRU缓存?(How to use LRU caching on disk with klepto?)

我正在尝试使用klepto来执行LRU缓存。 我想将缓存存储到磁盘,目前我正在使用klepto的dir_archive选项。 我写了下面的代码,主要基于klepto测试脚本中的代码:

def mymap(data):
    return hashlib.sha256(data).hexdigest()

class MyLRUCache:
    @lru_cache(cache=dir_archive(cached=False), keymap=mymap, ignore='self', maxsize=5)
    def __call__(self, data)
        return data

    call = __call__

    def store(self, data):
        self.call(data)

    # I would also appreciate a better way to do this, if possible.
    def lookup(self, key):
        return self.call.__cache__()[key]

此代码似乎正常工作,直到缓存达到maxsize 。 在这一点上, lru_cache不是使用LRU来删除单个项目, lru_cache清除整个缓存! 下面是一段klepto源代码( https://github.com/uqfoundation/klepto/blob/master/klepto/safe.py ):

# purge cache
if _len(cache) > maxsize:
    if cache.archived():
        cache.dump()
        cache.clear() 
        queue.clear()
        refcount.clear()
     else: # purge least recently used cache entry
        key = queue_popleft()
        refcount[key] -= 1
        while refcount[key]:
            key = queue_popleft()
            refcount[key] -= 1
        del cache[key], refcount[key]

所以我的问题是,为什么klepto清除“存档”缓存? 是否可以一起使用lru_cachedir_archive

另外,如果我的代码看起来完全是疯狂的,那么我真的很感激我应该写这个的一些示例代码,因为没有太多关于klepto的文档。

其他注意事项:我也试着用cached=True定义dir_archive 。 内存缓存在达到maxsize大小时仍会被清除,但缓存的内容将转储到此时的归档缓存中。 我有几个问题:

  1. 内存中的高速缓存只有在达到maxsize大小时才是准确的,在此时它会被擦除。
  2. 归档缓存不受maxsize影响。 内存缓存每次达到maxsize大小时,内存缓存中的所有项目都将转储到存档缓存,而不管已存在多少个缓存。
  3. 基于第1点和第2点,LRU缓存似乎是不可能的。

I am trying to use klepto to do LRU caching. I would like to store the cache to disk, and am currently using klepto's dir_archive option for this. I have written the following code, largely based on the code in the klepto test scripts:

def mymap(data):
    return hashlib.sha256(data).hexdigest()

class MyLRUCache:
    @lru_cache(cache=dir_archive(cached=False), keymap=mymap, ignore='self', maxsize=5)
    def __call__(self, data)
        return data

    call = __call__

    def store(self, data):
        self.call(data)

    # I would also appreciate a better way to do this, if possible.
    def lookup(self, key):
        return self.call.__cache__()[key]

This code appears to work fine until the cache reaches maxsize. At that point, instead of using LRU to remove a single item, lru_cache purges the entire cache! Below is the piece of klepto source code that does this (https://github.com/uqfoundation/klepto/blob/master/klepto/safe.py):

# purge cache
if _len(cache) > maxsize:
    if cache.archived():
        cache.dump()
        cache.clear() 
        queue.clear()
        refcount.clear()
     else: # purge least recently used cache entry
        key = queue_popleft()
        refcount[key] -= 1
        while refcount[key]:
            key = queue_popleft()
            refcount[key] -= 1
        del cache[key], refcount[key]

So my question is, why does klepto purge "archived" caches? Is it possible to use lru_cache and dir_archive together?

Also, if my code looks completely nuts, I would really appreciate some sample code of how I should be writing this, since there was not much documentation for klepto.

ADDITIONAL NOTES: I also tried defining dir_archive with cached=True. The in-memory cache still gets purged when maxsize is reached, but the contents of the cache are dumped to the archived cache at that point. I have several problems with this:

  1. The in-memory cache is only accurate until maxsize is reached, at which point it is wiped.
  2. The archived cache is not affected by maxsize. Every time maxsize is reached by the in-memory cache, all items in the in-memory cache are dumped to the archived cache, regardless of how many are already there.
  3. LRU caching seems impossible based on points 1 and 2.

原文:https://stackoverflow.com/questions/32081207
更新时间:2022-10-29 14:10

最满意答案

你可以将它们嵌套

map.resources :libraries do |library|
    library.resources :books do |book|
       book.resources :comments
    end
end

这可能令人困惑,但数据模型的多态性方面与路由无关。

要通过命名路线调用它们,对于评论,您需要提供一个库和一本书,即使它是明确的。


You just nest them:

map.resources :libraries do |library|
    library.resources :books do |book|
       book.resources :comments
    end
end

It may be confusing, but the polymorphic aspect of the data model is independent of the routes.

To call them via named routes, for a comment you'll need to provide a library and a book, even if it's unambiguous.

相关问答

更多
  • 类似的问题在这里: Django中的双重外键? 答案是在django中使用ContentTypes框架来实现多态关联。 similar question here: Double Foreign Key in Django? Answer is to use the ContentTypes framework in django to achieve polymorphic assocations.
  • 我在我的项目中做到了这一点。 诀窍在于,照片需要一列,用于在has_one条件下区分主要和次要照片。 注意发生的情况:conditions在这里。 has_one :photo, :as => 'attachable', :conditions => {:photo_type => 'primary_photo'}, :dependent => :destroy has_one :secondary_photo, :class_name => 'Photo', :as => 'attac ...
  • image_type在这个多态关联中有一个特定的功能......它标识关联的模型(就像image_id标识该id)。 你不应该改变image_type因为它会破坏关联。 在图片模型中创建一个新的布尔列,说cover_picture ,你可以做... has_one :cover_picture, -> {where cover_picture: true} ... 这样做的好处是你的封面图片也包含在你的图片关联中,但是如果你想从has_many中排除该图片,那么你可以应用一个where子句以及... ha ...
  • # Either one of these Result.create(result_table: self) Result.create(result_table_id: self.id, result_table_type: self.class.to_s) # Either one of these Result.create(result_table: self) Result.create(result_table_id: self.id, result_table_type: self.cla ...
  • 你可以将它们嵌套 map.resources :libraries do |library| library.resources :books do |book| book.resources :comments end end 这可能令人困惑,但数据模型的多态性方面与路由无关。 要通过命名路线调用它们,对于评论,您需要提供一个库和一本书,即使它是明确的。 You just nest them: map.resources :libraries do |library| ...
  • 我担心你的协会看起来完全错了。 首先,如果你在一个关联的一边有'has_many', 你必须在另一边有 'belongs_to'。 其次,我猜测done_user,admin_user等继承自User。 我对么 ? 参与者,admin_user等彼此之间有何不同? 你真的需要每个类的类,你能用命名范围吗? 我建议你简化你的数据模型。 现在你的建模模糊了。 请详细说明。 编辑 老实说,我认为你的建模过于复杂。 如果我是你,给定你对* _users的描述,我只会命名范围来检索该类型的用户。 所以实际上 clas ...
  • 您的问题的答案: 如果您的业务登录意味着多个模型将具有相同字段的相关模型,那么您应该使用多态关联。 (在你的情况下,你可以使用它)。 如果设置多态关联,Rails将根据关联的父模型自动处理设置*_id和*_type字段。 假设您在多态关联中有许多订单的产品,并且您想要定义哪个模型订单属于: order = Order.first order.orderable Answers to your questions: If your business login implies that multiple m ...
  • 1)如果将变量传递给partial,它将作为本地,而不是实例: <%= render :partial => 'comments/display', locals: {commentable: @article} %> 2)另请注意,从控制器渲染和从视图渲染是不同的事情。 在控制器中,您不必指定:partial=>因为Rails中的控制器应该呈现整个模板,但是如果您在视图文件中,则应该像Rails一样只能为每个请求呈现一个模板 1) If you pass variable to partial, it ...
  • 您可能想要使用某种中间记录,比如ActivityItem ,它位于ActivityFeed和Photo , Comment等之间...... class ActivityFeed < ActiveRecord::Base has_many :activity_items end class ActivityItem < ActiveRecord::Base belongs_to :activity_feed belongs_to :item, :polymorphic => true end ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)