请先看最后的纠正说明,谢谢
以前从来没有用过redis,现在有个任务需要使用redis,要求是能够根据index来删除key所对应的value list里面的值
def lrem(self, name, count, value):
"""
Remove the first ``count`` occurrences of elements equal to ``value``
from the list stored at ``name``.
The count argument influences the operation in the following ways:
count > 0: Remove elements equal to value moving from head to tail.
count < 0: Remove elements equal to value moving from tail to head.
count = 0: Remove all elements equal to value.
"""
return self.execute_command('LREM', name, count, value)
API 来自:redis-py client source code
redis-py API就是上面这样解释的。
然后我就认为第一个就是key,第二个参数就是说明里面的可以>0 , < 0 或 =0,最后一个是要删除的value值,
所有我写的code如下所示:
ret_code = redis_client.lrem(queue_name, 0, item)
打印ret_code的值始终为0,表示删除失败。我就很纳闷。通过redis-cli可以成功删除的
joey@ubuntu:~/workspace/py$ redis-cli
redis 127.0.0.1:6379> select 2
OK
redis 127.0.0.1:6379[2]> lrange list1 0 -1
1) "two"
2) "four"
3) "siz"
4) "seven"
5) "eight"
6) "nine"
7) "ten"
redis 127.0.0.1:6379[2]> lrem list 0 four
(integer) 0
redis 127.0.0.1:6379[2]> lrem list1 0 four
(integer) 1
redis 127.0.0.1:6379[2]> lrange list1 0 -1
1) "two"
2) "siz"
3) "seven"
4) "eight"
5) "nine"
6) "ten"
redis 127.0.0.1:6379[2]>
就是程序始终删除失败,网上搜索也搜不到相关主题内容。
后来我就活马当成死吗医,就把参数顺序随便那么一改,奇迹出现了。删除成功了,我回过头继续读源码解释,我现在在想,是我理解错了么??难道我英语真的差劲吗???
以下是我的测试程序:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import redis
import os
import sys
host = '127.0.0.1'
port = 6379
db = 2
queue_name = 'list1'
val = 'five'
def test():
redis_client = redis.Redis(host, port, db)
index = 0
job = None
for item in redis_client.lrange(queue_name, 0, -1):
if item.__eq__(val):
job = redis_client.lindex(queue_name, index)
result = redis_client.lrem(queue_name, job, 0)
print 'return code: ', result
break
index = index + 1
print '========================='
for item in redis_client.lrange(queue_name, 0, -1):
print item
if __name__=='__main__':
test()
========================================================
纠正:redis中有两个class,一个是Redis,一个是StrictRedis,
两个里面各有lrem方法:
Redis中的lrem方法:
lrem(name, value, num=0)
Remove the first num occurrences of elements equal to value from the list stored at name.
The num argument influences the operation in the following ways:
num > 0: Remove elements equal to value moving from head to tail. num < 0: Remove elements equal to value moving from tail to head. num = 0: Remove all elements equal to value.
StrictRedis中的lrem方法:
lrem(name, count, value)
Remove the first count occurrences of elements equal to value from the list stored at name.
The count argument influences the operation in the following ways:
count > 0: Remove elements equal to value moving from head to tail. count < 0: Remove elements equal to value moving from tail to head. count = 0: Remove all elements equal to value.
所以说之前是方法找错了。哎。。。。。。。。。。。