如何在Redis中保存复杂的数据结构?

2024-06-28 11:32:24 发布

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

我对Python还不熟悉。运行代码时出错:

import redis

def redisSave(case, key, ob):
    dataBase = None
    if case == 'Product':
        dataBase = redis.Redis(db=0)
        dataBase.set(key, ob)
        dataBase.expire(key, time=600)
    else:
        pass

dictOb = {
    'price': '2000 $',
    'weight': '50 lb'
}
redisSave('Product', 'first', dictOb)

它表示输入类型无效(redis.exceptions.DataError)你知道吗


Tags: key代码importredisnonedbifdef
2条回答

试试这个:

def redis_save(case, key, obj):
    data_base = None

    if case == 'Product':
        data_base = redis.Redis(db=0)

        if isinstance(obj, dict):
            data_base.hmset(key, obj)
            data_base.expire(key, time=600)

访问数据:data_base.hgetall('first')

结果:

{
    b'price': b'2000 $',
    b'weight': b'50 lb'
}

您还可以将数据存储为JSON转储pickle对象。参见:how to store a complex object in redis (using redis-py)。你知道吗

相关问题 更多 >