如何使用Flask-Restful Flask-Cache

时间:2014-07-18 03:31:27

标签: python redis flask-restful flask-cache cache-invalidation

如何在Flask-Restful中使用Flask-Cache @ cache.cached()装饰器?例如,我有一个继承自Resource的Foo类,而Foo有get,post,put和delete方法。

如何在POST

之后使缓存的结果无效
@api.resource('/whatever')
class Foo(Resource):
    @cache.cached(timeout=10)
    def get(self):
        return expensive_db_operation()

    def post(self):
        update_db_here()

        ## How do I invalidate the value cached in get()?
        return something_useful()

3 个答案:

答案 0 :(得分:3)

是的,你可以这样使用。

也许您仍然需要阅读:flask-cache memoize URL query string parameters as well

答案 1 :(得分:1)

您可以使用cache.clear()方法使缓存无效 有关详细信息,请参阅https://pythonhosted.org/Flask-Cache/#flask.ext.cache.Cache.clear

中的https://pythonhosted.org/Flask-Cache/和清除缓存部分

答案 2 :(得分:0)

##create a decarator
from werkzeug.contrib.cache import SimpleCache
CACHE_TIMEOUT = 300
cache = SimpleCache()
class cached(object):

 def __init__(self, timeout=None):
    self.timeout = timeout or CACHE_TIMEOUT

 def __call__(self, f):
    def decorator(*args, **kwargs):
        response = cache.get(request.path)
        if response is None:
            response = f(*args, **kwargs)
            cache.set(request.path, response, self.timeout)
        return response
    return decorator


#add this decarator to your views like below
@app.route('/buildingTotal',endpoint='buildingTotal') 
@cached()
def eventAlert():
  return 'something'

@app.route('/buildingTenants',endpoint='buildingTenants')
@cached()
def buildingTenants():
  return 'something'