我将 Flask Cache 插件与 Redis 一起用作后端来缓存我的 API 响应。假设我有这样的 API 来获取用户和创建用户:
/api/users?page=1 GET
/api/users POST
GET 结果将以完整 URL 作为键进行缓存。创建新用户时,我想删除所有以 /api/users
开头的键 - 目前我正在做 cache.clear()
但它几乎没有似乎有必要。
但是,我似乎无法找到获取 key 列表的 API。对于 redis-py
,有一个用于该目的的 keys(*pattern)
API。 Flask Cache 是否有类似的 API?
最佳答案
Flask-Cache looks outdated. You can switch to Flask-Caching which is maintained fork of Flask-Cache.
按模式删除Redis key
您有两个选择:
- 使用 redis 单独连接到 Redis包裹。使用包提供的核心命令根据模式搜索键,并删除它们。
- 使用 Flask-Cache 的 protected 方法/Flask-Caching获取对底层 Redis 对象的访问权限,并对该对象使用核心命令以根据模式搜索键并将其删除。
选项 1:单独连接到 Redis
# python utility for redis
import redis
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, password=REDIS_PASSWORD)
def delete_pattern(pattern: str) -> int:
"""Remove all keys matching pattern.
"""
count = 0
for key in r.scan_iter(pattern):
r.delete(key)
count += 1
return count
# pass pattern to delete
CACHE_URL_PAT = "flask_cache*auth*"
delete_pattern(CACHE_URL_PAT)
选项 2:使用 protected 方法来访问底层的 Redis 连接对象
⚠️ Even though this works fine, but these are undocumented methods. I went through the source code on GitHub to create this function. Tested only for CACHE_TYPE = 'redis'
# initialised cache object stored in extensions file
from app.extensions import cache
def delete_pattern(pattern):
status = False
binary_keys = cache.cache._read_clients.keys(pattern)
keys = [k.decode("utf-8", errors="ignore") for k in binary_keys if k]
if keys:
status = cache.cache._write_client.delete(*keys)
return status
# pass pattern to delete
CACHE_URL_PAT = "flask_cache*auth*"
delete_pattern(CACHE_URL_PAT)
注意:flask_cache_
在 Flask-Caching 中是默认的 CACHE_KEY_PREFIX
。如果您为 CACHE_KEY_PREFIX
使用了其他值,请使用它(而不是 flask_cache_
)作为搜索模式的前缀。
关于python - flask 缓存 : list keys based on a pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36708461/