在redis中保存unicode但获取错误 [英] Save unicode in redis but fetch error
问题描述
我正在使用 mongodb 和 redis,redis 是我的缓存.
I'm using mongodb and redis, redis is my cache.
我正在使用 redis-py 缓存 mongodb 对象:
I'm caching 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}
使用 hgetall(key, obj) 从 redis 获取的 obj 是:
the obj fetched from redis with hgetall(key, obj) is:
{'name': 'match', 'title': '\xe6\xaf\x94\xe8\xb5\x9b', 'section_title':
'\xe6\xb4\xbb\xe5\x8a\xa8', 'section_id': '1', '_id': '4fb1ed859b10ed2041000001', 'id': '1'}
如您所见,从缓存中获取的 obj 是 str 而不是 unicode,因此在我的应用程序中,存在如下错误:'ascii' codec can't decode byte 0xe6 in position 12: ordinal not in range(128)
As you can see, obj fetched from cache is str instead of unicode, so in my app, there is error s like :'ascii' codec can't decode byte 0xe6 in position 12: ordinal not in range(128)
谁能给点建议?谢谢你
推荐答案
更新,全局设置,查看jmoz 的回答.
如果你使用第三方库,比如django-redis
,你可能需要指定一个自定义的ConnectionFactory
:
If you're using third-party lib such as django-redis
, you may need to specify a customized 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
中的值即可.
Assuming you're using redis-py, you'd better to pass str
instead of unicode
to Redis, or else Redis will encode it automatically for *set
commands, normally in UTF-8. For the *get
commands, Redis has no idea about the formal type of a value and has to just return the value in str
directly.
因此,正如 Denis 所说,将对象存储到 Redis 的方式至关重要.您需要将值转换为 str
以使 Redis 层对您透明.
Thus, As Denis said, the way that you storing the object to Redis is critical. You need to transform the value to str
to make the Redis layer transparent for you.
另外,设置默认编码为UTF-8 而不是使用 ascii
这篇关于在redis中保存unicode但获取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!