V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
goofansu
V2EX  ›  Redis

在使用redis,python库是redis-py,保存到redis以后再取出,所有的unicode都变成了str类型,然后程序就报错了,请问有什么简单的方法可以在取出来的时候把字段都改回unicode吗?

  •  
  •   goofansu · 2012-05-15 11:35:07 +08:00 · 7965 次点击
    这是一个创建于 4364 天前的主题,其中的信息可能已经有所发展或是发生改变。
    google下,有些回答是在字符串前加u''或者unicode(str,'utf-8')方法转换,可是我现在因为使用的hmset和hgetall保存整个对象,取出也是整个对象,所以想问下有没有现成的方法可以进行转换的。取出如果是中文的话是这样的:
    {'name': 'match', 'title': '\xe6\xaf\x94\xe8\xb5\x9b', 'section_title': '\xe6\xb4\xbb\xe5\x8a\xa8', '_id': '4fb1c6329b10ed1adc000000', 'id': '1'}
    是英文的话就直接显示了英文

    报错还是老样子:
    'ascii' codec can't decode byte 0xe6 in position 12,
    5 条回复    2014-07-20 10:55:43 +08:00
    solowind
        1
    solowind  
       2012-05-15 12:05:13 +08:00   ❤️ 1
    习惯在写入和读取的时候都做unicode转码,用Python来保证,例如

    def _unicode(s):
    if isinstance(s, str):
    try:
    return s.decode('utf-8')
    except UnicodeDecodeError:
    pass
    return s

    Redis怎么配置不太清楚,这个代码好像是从Tornado里面找到的
    goofansu
        2
    goofansu  
    OP
       2012-05-15 12:11:14 +08:00
    @solowind 谢谢。数据在数据库中都是unicode的,可是保存到redis中它会自动转成str,再取出就不对了,网上搜了下也没搜出什么结果。
    gonbo
        3
    gonbo  
       2012-05-15 12:19:41 +08:00   ❤️ 1
    @goofansu redis-py的代码里面是做过encoding到utf-8的。不能encoding才str。你可以文件里面加上 # -*- coding: UTF-8 -*-
    goofansu
        4
    goofansu  
    OP
       2012-05-15 13:29:30 +08:00
    @gonbo 好的,我试试
    maga
        5
    maga  
       2014-07-20 10:55:43 +08:00
    ecode_responses=True 参数

    Looking into the StrictRedis.__init__ there is a parameter decode_responses which by default is False. https://github.com/andymccurdy/redis-py/blob/master/redis/client.py#L284 (line num may change in future, look in __init__).

    Pass in decode_responses=True on construct and for me this FIXES THE OP'S ISSUE.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3926 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 05:11 · PVG 13:11 · LAX 22:11 · JFK 01:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.