如何在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()
答案 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
答案 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'