Redis Python-如何在python中根据特定模式删除所有键,而无需python迭代 [英] Redis Python - how to delete all keys according to a specific pattern In python, without python iterating

查看:72
本文介绍了Redis Python-如何在python中根据特定模式删除所有键,而无需python迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写django管理命令来处理一些我们的redis缓存.基本上,我需要选择所有确认为特定模式的键(例如:"prefix:*")并删除它们.

I'm writing a django management command to handle some of our redis caching. Basically, I need to choose all keys, that confirm to a certain pattern (for example: "prefix:*") and delete them.

我知道我可以使用cli来做到这一点:

I know I can use the cli to do that:

redis-cli KEYS "prefix:*" | xargs redis-cli DEL

但是我需要在应用程序中执行此操作.所以我需要使用python绑定(我正在使用py-redis).我曾尝试将列表送入Delete列表,但失败了:

But I need to do this from within the app. So I need to use the python binding (I'm using py-redis). I have tried feeding a list into delete, but it fails:

from common.redis_client import get_redis_client
cache = get_redis_client()
x = cache.keys('prefix:*') 

x == ['prefix:key1','prefix:key2'] # True

#现在

cache.delete(x) 

#返回0.什么都不会删除

# returns 0 . nothing is deleted

我知道我可以遍历x:

for key in x:
   cache.delete(key)

但是那会失去redis的超快速度并滥用其功能.是否有使用py-redis的pythonic解决方案,而没有迭代和/或cli?

But that would be losing redis awesome speed and misusing its capabilities. Is there a pythonic solution with py-redis, without iteration and/or the cli?

谢谢!

推荐答案

我认为

 for key in x: cache.delete(key)

非常简洁. delete 确实一次只想要一个键,所以您必须循环.

is pretty good and concise. delete really wants one key at a time, so you have to loop.

否则,这先前的问题和答案为您提供基于lua的解决方案.

Otherwise, this previous question and answer points you to a lua-based solution.

这篇关于Redis Python-如何在python中根据特定模式删除所有键,而无需python迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆