1
@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. 上面的代码运行,但有错误并且没有按需要执行。坦率地说,flask-cache 文档没有帮助。如何正确实现 cache.set 和 cache.get 以根据需要执行?

4

1 回答 1

3

In Flask, implementing your custom cache wrapper is very simple.

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)

Also, the simple memory cache is for single process environments and the SimpleCache class exists mainly for the development server and is not 100% thread safe. In production environments you should use MemcachedCache or RedisCache.

Make sure you implement logic when item is not found in the cache.

于 2015-07-14T02:15:19.783 回答