Save unicode in redis but fetch error

I use mongodb and redis, redis is my cache.

I cache mongodb objects with redis-py:

obj in mongodb: {u'name': u'match', u'section_title': u'\u6d3b\u52a8', u'title': 
u'\u6bd4\u8d5b', u'section_id': 1, u'_id': ObjectId('4fb1ed859b10ed2041000001'), u'id': 1}

obj obtained from redis using hgetall (key, obj):

{'name': 'match', 'title': '\xe6\xaf\x94\xe8\xb5\x9b', 'section_title': 
'\xe6\xb4\xbb\xe5\x8a\xa8', 'section_id': '1', '_id': '4fb1ed859b10ed2041000001', 'id': '1'}

As you can see, obj extracted from the cache is str instead of unicode, so there is an error like in my application: the ascii codec cannot decode the 0xe6 byte at position 12: the serial number is not in the range (128)

Can anyone give any suggestions? thanks u

+5
source share
4 answers

Refresh, for global settings, check jmoz answer .

If you use a third-party library, for example django-redis, you may need to specify a custom one ConnectionFactory:

class DecodeConnectionFactory(redis_cache.pool.ConnectionFactory):
    def get_connection(self, params):
        params['decode_responses'] = True
        return super(DecodeConnectionFactory, self).get_connection(self, params)

, redis-py, str unicode Redis, Redis *set, UTF-8. *get Redis str.

, , , Redis. str, Redis .

, UTF-8 ascii

+7

, . , redis, , .

, - , .

StrictRedis.__init__ decode_responses, False. https://github.com/andymccurdy/redis-py/blob/273a47e299a499ed0053b8b90966dc2124504983/redis/client.py#L446

decode_responses=True, FIXES OP OPTION.

+25

decode utf-8, . , :

In [7]: a='\xe6\xaf\x94\xe8\xb5\x9b'

In [8]: a.decode('utf8')
Out[8]: u'\u6bd4\u8d5b'
+6

utf-8 , MongoDB Redis ( ). ( "utf-8" ), fecth, Unicode Python.

+3

All Articles