@app.route('/path/<user>/<id>', methods=['POST'])
@cache.cached(key_prefix='/path/<user>', unless=True)
def post_kv(user, id):
cache.set(user, id)
return value
@app.route('/path/<user>', methods=['GET'])
@cache.cached(key_prefix='/path/<user>', unless=True)
def getkv(user):
cache.get(**kwargs)
我希望能够对所描述的路径进行POST调用,存储它们,并从user
获取它们的值。上面的代码运行,但有错误,并没有按需执行。坦率地说,烧瓶缓存文档没有帮助。如何正确实现cache.set和cache.get以根据需要执行?
答案 0 :(得分:2)
在Flask中,实现自定义缓存包装非常简单。
from werkzeug.contrib.cache import SimpleCache, MemcachedCache
class Cache(object):
cache = SimpleCache(threshold = 1000, default_timeout = 100)
# cache = MemcachedCache(servers = ['127.0.0.1:11211'], default_timeout = 100, key_prefix = 'my_prefix_')
@classmethod
def get(cls, key = None):
return cls.cache.get(key)
@classmethod
def delete(cls, key = None):
return cls.cache.delete(key)
@classmethod
def set(cls, key = None, value = None, timeout = 0):
if timeout:
return cls.cache.set(key, value, timeout = timeout)
else:
return cls.cache.set(key, value)
@classmethod
def clear(cls):
return cls.cache.clear()
...
@app.route('/path/<user>/<id>', methods=['POST'])
def post_kv(user, id):
Cache.set(user, id)
return "Cached {0}".format(id)
@app.route('/path/<user>', methods=['GET'])
def get_kv(user):
id = Cache.get(user)
return "From cache {0}".format(id)
此外,简单内存缓存适用于单进程环境,SimpleCache类主要用于开发服务器,并且不是100%线程安全的。在生产环境中,您应该使用MemcachedCache或RedisCache。
确保在缓存中找不到项目时实现逻辑。