我需要将一个小dict对象保存到磁盘,其对象的类型str和值是ints ,然后恢复它.像这样的东西:
{'juanjo': 2, 'pedro':99, 'other': 333}
Run Code Online (Sandbox Code Playgroud)
什么是最好的选择,为什么?用pickle或用simplejson?序列化?
我使用的是Python 2.6.
我想使用Redis的-PY缓存一些数据,但我无法找到之间的差异的一个合适的解释redis.StrictRedis()和redis.Redis().它们是等价的吗?
另外,我redis.StrictRedis()在Redis Python Docs中找不到关于参数的任何明确文档.任何的想法?
我试图检查对象是否是JSON可序列化的,因为我有一个包含大量内容的字典,此时它更容易遍历其键并查找它们是否是JSON可序列化并删除它们.像(虽然这检查它的功能):
def remove_functions_from_dict(arg_dict):
'''
Removes functions from dictionary and returns modified dictionary
'''
keys_to_delete = []
for key,value in arg_dict.items():
if hasattr(value, '__call__'):
keys_to_delete.append(key)
for key in keys_to_delete:
del arg_dict[key]
return arg_dict
Run Code Online (Sandbox Code Playgroud)
是否有一种方法,if语句代替检查JSON可序列化对象,并以类似于上面的方式从字典中删除它们?
我设置了 Django & Redis 项目并尝试在 Redis 中存储 Django 模型对象。如果我django.core.cache如下使用,card2 被正确设置为 django 对象。但是,如果我使用 django_redis 提供的原始 redis 连接,它会获取 django 模型对象的字符串表示。
我将两个键设置如下。如何使用原始 redis 连接来获取卡对象本身而不是其字符串 repr?我需要它,因为我想使用mget,zrange比如 redis.py 的方法。
from django.core.cache import cache
from django_redis import get_redis_connection
con = get_redis_connection("default")
card = Card.objects.all()[0]
key = "card_" + str(card.id)
con.delete(key)
cache.delete(key)
con.set(key, card)
cache.set(key, card)
card1 = con.get(key)
card2 = cache.get(key)
Run Code Online (Sandbox Code Playgroud) 我正在尝试在Redis中存储一个自定义的,可序列化的python对象,但遇到了一些奇怪的行为.该set方法似乎起作用,但该get方法仅返回对象__repr__方法的值.例如...
import redis
# initialize the redis connection pool
rs = redis.Redis(host='localhost', port=6379)
# define a custom class
class SomeCustomObject(object):
pass
Run Code Online (Sandbox Code Playgroud)
当我尝试将其设置SomeCustomObject为值时,它似乎工作:
>>> rs.set('c', SomeCustomObject())
True
Run Code Online (Sandbox Code Playgroud)
但是,当我get返回值时,它只是__repr__字符串:
>>> rs.get('c')
'<__main__.SomeCustomObject object at 0x102496710>'
Run Code Online (Sandbox Code Playgroud)
如何存储/获取实例?我没有太多运气在文档中找到任何相关信息,但我肯定不是第一个遇到这个问题的人吗?
我正在使用 redis-py,每当我在缓存中存储列表或字典时,运行 get 函数都会返回一个字符串。如何取回原始数据类型?
cache = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)
cache.set("posts",[["bob","My first post"],["mary","My second post"]])
cache.get("post")
>>>"[["bob","My first post"],["mary","My second post"]]"
Run Code Online (Sandbox Code Playgroud)
这是我必须手动做的事情吗?
我一直在遇到存储更复杂信息的情况,而不是Redis的任何简单数据结构.我仍然想使用Redis,但我想知道是否有人使用的标准替代品,理想情况下他们想使用嵌套结构?