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. 上記のコードは実行されますが、バグがあり、必要に応じて実行されません。率直に言って、フラスコキャッシュのドキュメントは役に立ちません。必要に応じて cache.set と cache.get を適切に実装するにはどうすればよいですか?

4

1 に答える 1

3

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 を使用する必要があります。

アイテムがキャッシュに見つからない場合は、必ずロジックを実装してください。

于 2015-07-14T02:15:19.783 に答える