supermario supermario - 1 year ago 154
Python Question

How to save/get redis hash key as unicode?

When I get a hash map key:value from redis, it turns out to be like:

hmgetall {'<a href="/topic/\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3-\xd8\xaa\xd8\xb3\xd8\xaa">\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3 \xd8\xaa\xd8\xb3\xd8\xaa</a>': '1'}

While it is saved as unicoe in python.

So I'm wondering how to save the hash key as unicode so that it can be compared with unicode strings?

I'd like the key to be saved into it's unicode format which is:

key = '<a href="/topic/\u0631\u062f\u06cc\u0633-\u062a\u0633\u062a">\u0631\u062f\u06cc\u0633 \u062a\u0633\u062a</a>'

Or, otherwise, I'd like to be able to convert the key to
format so that I can compare it with redis' saved key.

I've looked at the docs but could not find hints about this.

Answer Source

Assuming you're using Python 2, and the keys/values are encoded as utf-8:

>>> redis_key = '<a href="/topic/\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3-\xd8\xaa\xd8\xb3\xd8\xaa">\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3 \xd8\xaa\xd8\xb3\xd8\xaa</a>'
>>> redis_key.decode('utf-8')
u'<a href="/topic/\u0631\u062f\u06cc\u0633-\u062a\u0633\u062a">\u0631\u062f\u06cc\u0633 \u062a\u0633\u062a</a>'

To encode an existing key:

>>> key = u'<a href="/topic/\u0631\u062f\u06cc\u0633-\u062a\u0633\u062a">\u0631\u062f\u06cc\u0633 \u062a\u0633\u062a</a>'
>>> key.encode('utf-8')
'<a href="/topic/\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3-\xd8\xaa\xd8\xb3\xd8\xaa">\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3 \xd8\xaa\xd8\xb3\xd8\xaa</a>'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download