redis之列表操作及在django中操作等相關內容-124
阿新 • • 發佈:2021-01-07
import redis
#
# class MyRedis():
# def __enter__(self):
# self.conn = redis.Redis()
# return self.conn
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# self.conn.close()
#
#
# with MyRedis() as conn:
# 列表操作
# 1 lpush(name,values)
# conn.lpush('l1',1,2,3,4,5,'lqz')
# 2 rpush
# conn.rpush('l1','egon')
# 3 lpushx(name,value)
# 在name對應的list中新增元素,只有name已經存在時,值新增到列表的最左邊
# conn.lpushx('l2',9)
# conn.lpushx('l1',9)
# llen(name)
# res=conn.llen('l1')
# print(res)
# linsert(name, where, refvalue, value)) 在某個位置插入值
# where :BEFORE或AFTER,大小寫都行
# refvalue: lqz 表示以lqz為標準(不是下標索引)
# conn.linsert('l1','after','lqz','劉亦菲')
# conn.linsert('l1','before','lqz','baby')
# lset
# conn.lset('l1',0,'黃曉明')
# conn.lset('l1',5,'老夥計')
# lrem
# 第二個引數count:
# count = 0,刪除列表中所有的指定值;
# count=2,從前到後,刪除2個;
# count=-2,從後向前,刪除2個
# conn.lrem('l1',0,'lqz') # 把所有lqz都刪除
# conn.lrem('l1',2,'lqz') # 從前往後,刪除2個lqz
# conn.lrem('l1',-1,'lqz') # 從前往後,刪除2個lqz
# lpop
# res=conn.lpop('l1')
# res=conn.rpop('l1')
# print(res)
# lindex(不刪除)
# res=conn.lindex('l1',0)
# print(res)
# lrange # 前閉後閉區間
# res = conn.lrange('l1', 0, 0)
# print(res)
# ltrim
# res=conn.ltrim('l1',3,5)
# print(res)
# rpoplpush 需要兩個列表
# conn.lpush('l2','lqz','egon')
# conn.rpoplpush('l1','l1')
# blpop # block:阻塞 左邊彈出
# res=conn.blpop('l1')
# print(res)
'''
lpush
llen
linsert
lset
lrem
lpop
lrange # 使用它,自定義增量迭代
blpop
'''
### redis類庫中沒有提供對列表元素的增量迭代,藉助lrange
import redis
conn = redis.Redis()
# res=conn.lrange('l2',0,9999) # 全部取出來
# res=conn.lrange('l2',0,conn.llen('l2')) # 從0取到列表長度
# 類似於字典的hgetall,一次性全取出來,存在的問題是,因為不知道列表有多大,很有可能撐爆記憶體
# 我們實現一個增量迭代
# print(res)
# for i in range(10000):
# conn.lpush('l_test','test_%s'%i)
# res=conn.lrange('l2',0,conn.llen('l2'))
# print(res)
# res = conn.lrange('l_test', 0, 9)
# print(res)
# def lscan_iter(name, conn, count=10):
# cursor = 0
# lenght = conn.llen(name) # 計算列表總長度
# while cursor < lenght:
# data = conn.lrange(name, cursor, (cursor+count) - 1)
# cursor += count
#
# for item in data:
# yield item