pythonic way deal with DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.?
Asked Answered
P

2

7

redis veersion 3.4.1 must be use hash, can't use str or other data type data:

{
    '_anno': {
        'ctp': 'list',
        'dt': [],
        'ml': 0,
        'na': 'apple',
        'pos': -1,
        'rel': '',
        'st_var': '',
        'tp': 'object'
    },
    '_att': {
        '_cuser': 'apple card',
        '_last_editor': 'apple card',
        '_protext': 'authorize',
        '_status': 'normal',
        '_theme_id': 'apple card',
        '_view': '12'
    }
}

my code

pool = redis.ConnectionPool(host=host, port=port)
conn = redis.StrictRedis(connection_pool=pool)

conn.hmset("aaaaaa",data)

raise error

DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.

now code

pool = redis.ConnectionPool(host=host, port=port)
conn = redis.StrictRedis(connection_pool=pool)
new_data={}
for key,value in data.items():
    new_data[key]=json.dumps(value)
conn.hmset("aaaaaa",new_data)

Is there a more pythonic way?

Postilion answered 26/2, 2020 at 8:47 Comment(1)
Using map() instead of loop is more pythonic way to do such things. See #12229564.Jolt
S
1

The solution for you problem is to use hexdigest() or digest() to convert your dictionary, you can use that:

hashlib.sha256(mdp.encode()).hexdigest()
Saltish answered 16/2, 2021 at 19:1 Comment(2)
Can you reference the docs about using .hexdigest() for feeding Redis?Subterrane
Yes, you can consult: docs.python.org/3/library/hashlib.htmlSaltish
S
0

Maybe a more pythonic way would be something like:

pool = redis.ConnectionPool(host=host, port=port)
conn = redis.StrictRedis(connection_pool=pool)
new_data=dict(k, json.dumps(v) for (k, v) in data.items())
conn.hmset("aaaaaa", new_data)

but it very depends on how the original dictionary is built:

if all its values are dictionaries, then that's ok; but it they are mixed values, you should consider dumping selected values explicitely:

...
new_data = {
    '_anno': json.dumps(data['_anno']),
    '_att': json.dumps(data['_att']),
    'int_value': data['int_value'],
    'str_value': data['str_value'],
    ...
}

Maybe you can also find some generic solution:

SAFE_TYPES = (int, str, bool, bytes, float)
new_data = {
    k: v if isinstance(v, SAFE_TYPES) else json.dumps(v)
    for k, v in data.items()
}
Subterrane answered 13/3, 2023 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.