Search code examples
pythonflaskflask-cache

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. The above code runs, but has bugs and doesn't perform as needed. Frankly, the flask-cache docs aren't helping. How can I properly implement cache.set and cache.get to perform as needed?


Solution

  • 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.