烧瓶缓存:基于模式列出密钥? [英] flask cache: list keys based on a pattern?
问题描述
我将Flask Cache插件与Redis用作后端来缓存我的API响应.假设我有API可以吸引用户并像这样创建用户:
I'm using the Flask Cache plugin with Redis as backend to cache my API response. Say I have APIs to get users and create user like this:
/api/users?page=1 GET
/api/users POST
将以完整URL作为键来缓存GET结果.创建新用户后,我想删除所有以/api/users
开头的键-当前,我正在执行 cache.clear()
,但几乎没有似乎是必要的.
The GET result will be cached with full URL as key. When a new user is created, I'd like to delete all keys that start with /api/users
- currently I'm doing cache.clear()
but it hardly seems necessary.
但是,我似乎找不到用于获取键列表的API.使用 redis-py
时,有一个 keys(* pattern)
API用于此目的.Flask Cache是否有类似的API?
However, I can't seem to find an API to get a list of keys. With redis-py
, there is a keys(*pattern)
API for that purpose. Is there a similar API for Flask Cache?
推荐答案
Flask-Cache看起来已经过时了.您可以切换到烧瓶缓存,它是Flask-Cache的分支.
Flask-Cache looks outdated. You can switch to Flask-Caching which is maintained fork of Flask-Cache.
按模式删除Redis键
您有两个选择:
- 使用 redis 软件包分别连接到Redis.使用程序包提供的核心命令根据模式搜索键,然后将其删除.
- 使用Flask-Cache的受保护方法/烧瓶缓存可以访问底层Redis对象,并使用该对象上的核心命令来基于模式搜索键并将其删除.
- Connect to Redis separately using the redis package. Use core commands provided by the package to search for keys based on a pattern, and delete them.
- Use protected methods of the Flask-Cache / Flask-Caching to get access to the underlying Redis object, and use core commands on that object to search for keys based on a pattern, and delete them.
选项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:使用受保护的方法来访问底层的Redis连接对象
⚠️即使此方法工作正常,但这些都是未记录的方法.我在GitHub上浏览了源代码来创建此功能.仅针对CACHE_TYPE ='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-Caching中, flask_cache _
是默认的 CACHE_KEY_PREFIX
.如果您对 CACHE_KEY_PREFIX
使用了其他值,请使用该值(而不是 flask_cache _
)作为搜索模式的前缀.
NOTE : flask_cache_
is default CACHE_KEY_PREFIX
in Flask-Caching. If you have used some other value for CACHE_KEY_PREFIX
, please use that (instead of flask_cache_
) as the prefix for your search pattern.
这篇关于烧瓶缓存:基于模式列出密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!