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?

Don
  • 16,928
  • 12
  • 63
  • 101
xin.chen
  • 964
  • 2
  • 8
  • 24
  • Using map() instead of loop is more pythonic way to do such things. See https://stackoverflow.com/questions/12229064/mapping-over-values-in-a-python-dictionary. – Zbyszek Feb 26 '20 at 09:53

2 Answers2

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()
StarGit
  • 35
  • 14
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()
}
Don
  • 16,928
  • 12
  • 63
  • 101