python,redis:在redis上存储一个多维列表。最佳数据类型?

2024-09-28 17:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要定期存储一个python列表

[
[1, ...],
[2, ...],
[3, ...],
[4, ...]
]
  1. 我需要让它在几秒钟后过期并添加一个新的(所以我想创建一个列表并使用python列表立即填充它)。在
  2. 我需要检索特定范围的子列表,例如:[[2, ...], [3, ...]]

使用this library我考虑使用lpush立即创建并填充列表,expire在我创建并填充列表后设置过期时间,lrange以获取python子列表的特定范围

我是在使用一个好的解决方案,还是有更适合我需要的解决方案?在


Tags: 列表library时间解决方案this几秒钟expirelpush
2条回答

就用泡菜吧

# store_objects_in_redis.py
'''
 Pickle (dumps) & set to store
 Get & and unpickle (loads) to retrieve
 #
 Courtesy: Armin Ronacher, http://flask.pocoo.org/snippets/73/ 
'''

import redis
from pickle import loads, dumps

# Create client with default connection
client = redis.client.StrictRedis()
# An example complex object
stored_object = [{1,2,3}, {'a':1,'b':2,'c':3}, ['foo', 'bar']]

# store
client.set('obj', dumps(stored_object))

# retrieve
retrieved_object = loads(client.get('obj'))

# compare
print(stored_object==retrieved_object, '\n', stored_object, '\n', retrieved_object)

'''
Prints (Running in windows7)
== RESTART: K:/.../REDIS/store_objects_in_redis.py ==
True 
 [{1, 2, 3}, {'c': 3, 'b': 2, 'a': 1}, ['foo', 'bar']] 
 [{1, 2, 3}, {'c': 3, 'b': 2, 'a': 1}, ['foo', 'bar']]

'''

Redis只支持一级数据结构,但可以使用Json打破规则。因此,您可以将每个内部列表设置为一个json字符串,并使用redis list进行存储。在

相关问题 更多 >