python redis 分页

本文介绍了如何利用Redis的SortedSet和Hash数据结构实现高效的数据排序和分页处理。通过实例演示了如何将时间戳作为分数存储在SortedSet中,并使用Hash存储详细信息,最后通过排序和获取操作实现了数据的分页展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用SortedSet 和 Hash 进行分页处理

import json

from redis import ConnectionPool, StrictRedis
import time, datetime

pool = ConnectionPool(host='192.168.2.122', port=6379, db=0)
# 由于redis输出数据类型是bytes,所以连接配置提供decode_responses选项,可以选择直接输出str类型数据
redis = StrictRedis(connection_pool=pool, decode_responses=True)


if __name__ == '__main__':
    # redis 的SortedSet 是通过分数来排序的
    # 分数 用 时间戳来代替
    t = time.time()
    redis.zadd('subject', {'Chinese': t})
    # 将内容存储到 Hash
    dic = {
        'subject': 'Chinese',
        'ins': "语文课",
    }
    dump = json.dumps(dic)
    redis.hset("subject_ins", "Chinese", dump)
    t = time.time()
    redis.zadd('subject', {'Math': t})
    dic = {
        'subject': 'Math',
        'ins': "数学课",
    }
    dump = json.dumps(dic)
    redis.hset("subject_ins", "Math", dump)
    t = time.time()
    redis.zadd('subject', {'Physics': t})
    dic = {
        'subject': 'Physics',
        'ins': "物理课",
    }
    dump = json.dumps(dic)
    redis.hset("subject_ins", "Physics", dump)
    zrange = redis.zrange('subject', 0, 1, desc=False, withscores=True)
    print(zrange)
    zrange = list(map(lambda x: str(x[0], encoding='utf-8'), zrange))
    # 按排序 获取subject
    print(zrange)
    # 获取hash
    subject_ins = redis.hmget('subject_ins', zrange)
    subject_ins = list(map(lambda x: json.loads(str(x, encoding='utf-8')), subject_ins))
    print(subject_ins)

结果

[(b'Chinese', 1550712359.4595), (b'Math', 1550712359.464)]
['Chinese', 'Math']
[{'subject': 'Chinese', 'ins': '语文课'}, {'subject': 'Math', 'ins': '数学课'}]

 

转载于:https://my.oschina.net/xiaohuai4869/blog/3012780

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值