goofansu
V2EX  ›  Redis

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

  •  
  •   goofansu · May 15, 2012 · 8821 views
    This topic created in 5118 days ago, the information mentioned may be changed or developed.
    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 replies    2014-07-20 10:55:43 +08:00
    solowind
        1
    solowind  
       May 15, 2012   ❤️ 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
       May 15, 2012
    @solowind 谢谢。数据在数据库中都是unicode的,可是保存到redis中它会自动转成str,再取出就不对了,网上搜了下也没搜出什么结果。
    gonbo
        3
    gonbo  
       May 15, 2012   ❤️ 1
    @goofansu redis-py的代码里面是做过encoding到utf-8的。不能encoding才str。你可以文件里面加上 # -*- coding: UTF-8 -*-
    goofansu
        4
    goofansu  
    OP
       May 15, 2012
    @gonbo 好的,我试试
    maga
        5
    maga  
       Jul 20, 2014
    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.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1805 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 16:15 · PVG 00:15 · LAX 09:15 · JFK 12:15
    ♥ Do have faith in what you're doing.