简体   繁体   English

flask:如何存储和检索POST调用?

[英]flask: How to store and retrieve POST calls?

@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)

I want to be able to make POST calls to the path described, store them, and GET their values from the user . 我希望能够对所描述的路径进行POST调用,存储它们并从user获取它们的值。 The above code runs, but has bugs and doesn't perform as needed. 上面的代码可以运行,但是有错误并且不能按需执行。 Frankly, the flask-cache docs aren't helping. 坦白说,flask-cache文档没有帮助。 How can I properly implement cache.set and cache.get to perform as needed? 如何正确实现cache.set和cache.get以根据需要执行?

In Flask, implementing your custom cache wrapper is very simple. 在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)

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. 另外,简单内存缓存用于单进程环境,而SimpleCache类主要存在于开发服务器中,并且不是100%线程安全的。 In production environments you should use MemcachedCache or RedisCache. 在生产环境中,应使用MemcachedCache或RedisCache。

Make sure you implement logic when item is not found in the cache. 确保在缓存中未找到项目时实现逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM