Django中的cache.fetch? [英] cache.fetch in Django?

查看:136
本文介绍了Django中的cache.fetch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django缓存有一个类似于Rails的cache.fetch的方法吗? ( http://api.rubyonrails.org/classes/ActiveSupport/Cache /Store.html#M001023
rails缓存提取的工作原理如下:

 
cache.fetch(my_key ){
//返回我想要放在my_key中的空值
some_value
}

它有用,因为它检查缓存,并返回缓存的值,如果它在那里。如果没有,它将在缓存中存储some_value,然后返回some_value。



Django中是否有相当于此?如果没有,那么这个Python语法怎么样呢,如果我要实现这样一个函数?

解决方案

我认为代码你必须这样写:(EDIT)

  def get_value(param1,param2):
return value%s - %s%(str(param1),str(param2))

def fetch(key,val_function,** kwargs)
val = cache.get )
如果不是val:
val = val_function(** kwargs)
cache.set(key,val)
return val

,您可以这样称呼:

  fetch('key',get_value,param1 ='first',param2 ='second')


Does Django caching have a method similar to Rails' cache.fetch? (http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#M001023) The rails cache fetch works like:

cache.fetch("my_key") {
  // return what I want to put in my_key if it is empty
  "some_value"
}

It's useful because it checks the cache, and returns the value of the cache if it is there. If not, it will store "some_value" in the cache, and then return "some_value".

Is there an equivalent of this in Django? If not, what would the Python syntax for this look like if I were to implement such a function?

解决方案

I think the code you would have to write would be like this: (EDIT)

def get_value(param1,param2):
    return "value %s - %s " % (str(param1),str(param2))

def fetch(key,val_function,**kwargs)
    val = cache.get(key)
    if not val:
        val = val_function(**kwargs)
        cache.set(key,val)
    return val

and you would call it like this:

fetch('key',get_value,param1='first',param2='second')

这篇关于Django中的cache.fetch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆