在python中使用列表字典和嵌套字典实现hmset



我试图将以下redis代码实现为python django应用程序
hmset test_template:TEMPLATE_ID test_tags "[{"key":"test_manual_entry_1","value":"Some_value_1"},{"key":"test_manual_entry_2","value":"Some_value_2"}]"

我已经尝试了hsethmset函数,但两者都给出了错误。下面是我的代码示例,看起来像这样

class RedisUtil:
def hset(self, key_name, data):
key_name = "test_template:TEMPLATE_ID"
list_data = [{"key": "test_manual_entry_1", "value": "Some_value1"}, {"key": "test_manual_entry_2", "value": "Some_value2"}]
data = {"test_tags": [json.dumps(d) for d in list_data]}  # output list: ['{"key": "test_manual_entry_1", "value": "Some_value1"}', '{"key": "test_manual_entry_2", "value": "Some_value2"}']

我尝试了下面的方法来保存,但所有的方法都给我错误

# Method 1
self.redis_client.hset(key_name, data)  # Exception: redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
#Method 2
self.redis_client.hset(key_name, "test_tag", data["test_tags"])  # Exception: redis.exceptions.DataError: Invalid input of type: 'list'. Convert to a bytes, string, int or float first.

另外,我想在这里补充一点,可能存在我的列表为空的情况,这可能是一个边缘情况。

提前感谢您的帮助。

这里是Python Redis hset doc: https://redis.readthedocs.io/en/stable/commands.html?highlight=hset#redis.commands.core.CoreCommands.hset

功能签名为hset(name, key=None, value=None, mapping=None, items=None)

对于方法1,您传递data作为键。此外,我假定data是一个字典,它不同于string。

对于方法2,您使用data["test_tags"]作为值,但是,data["test_tags"]仍然不是字符串,而是一个列表。

如果你想实现hmset,可能你应该使用这个代替(但已经弃用,不推荐)?

最新更新