【问题标题】:Decoding URL containing unicode characters解码包含 Unicode 字符的 URL
【发布时间】:2012-12-24 10:09:54
【问题描述】:

我在 Mako 模板中有以下代码:

<a href="#" onclick='getCompanyHTML("${fund.investments[inv_name].name | u}"); return false;'>${inv_name}</a>

这会将 url 转义应用于代表公司的对象的名称字符串。然后在 url 中使用生成的转义字符串。 Mako 文档指出,url 编码是使用urllib.quote_plus(string.encode('utf-8')) 提供的。

在服务器上,我在参数investment_name 中收到公司名称部分:

def Investment(client, fund_name, investment_name, **kwargs):
    client          = urllib.unquote_plus(client)
    fund_name       = urllib.unquote_plus(fund_name)
    investment_name = urllib.unquote_plus(investment_name)

然后,我使用investment_name 作为键返回到模板中从中提取它的同一个字典。

这适用于所有标准情况,例如公司名称中的空格、斜杠和单引号。但是,如果公司名称包含 ascii 字符集之外的 unicode 字符,则会失败。

例如,公司名称“Eptisa Servicios de Ingeniería S.L.”的网址呈现为“Eptisa+Servicios+de+Ingenier%C3%ADa+S.L.”当此值返回服务器时,我正在反转 url 转义但显然无法正确解码 unicode,因为我尝试将结果用作字典键会产生键错误。

我试过以这两种形式添加 unicode 解码,但没有运气:

    investment_name = urllib.unquote_plus(investment_name.decode('utf-8'))
    investment_name = urllib.unquote_plus(investment_name.encode('raw_unicode_escape').decode('utf-8'))

谁能建议我必须对“Eptisa+Servicios+de+Ingenier%C3%ADa+S.L.”做什么把它改回“Eptisa Servicios de Ingeniería S.L.”?

【问题讨论】:

    标签: unicode python-2.7 escaping cherrypy mako


    【解决方案1】:

    以相反的顺序执行:首先取消引用然后.decode('utf-8')

    不要混合使用字节和 Unicode 字符串。

    示例

    import urllib
    
    q = "Eptisa+Servicios+de+Ingenier%C3%ADa+S.L."
    b = urllib.unquote_plus(q)
    u = b.decode("utf-8")
    print u
    

    注意:print u 可能会产生 UnicodeEncodeError。修复它:

    print u.encode(character_encoding_your_console_understands)
    

    或者设置PYTHONIOENCODING环境变量。

    在 Unix 上,您可以尝试将 locale.getpreferredencoding() 作为字符编码,在 Windows 上查看 chcp 的输出

    【讨论】:

    • 当我执行 urllib.unquote_plus(investment_name).decode('utf-8') 时,我会从 .decode('utf-8') 调用中的编解码器模块中获得 UnicodeEncodeError: 'ascii' codec can't encode characters in position 28-29: ordinal not in range(128)
    • @LarryLustig:试试上面的代码示例。哪一行产生错误?是print u吗?
    • 现在试试。我知道我无法将 unicode 字符串打印到我的术语中,但如果我可以让解码工作我应该没问题(我将通过使用结果作为字典中的键来确认)。感谢您的帮助,很快就会有结果。 . .
    • 结果:您的代码完美运行(包括打印 Windows 命令控制台,如图)。再深入一点,我看到我正在取消引用和解码的字符串(您的示例代码中的q)是 unicode,而我假设在您的示例中它是字符串(我使用的是 2.7)。如果我将您的代码转换为 Unicode 字符串 q,它就像我的代码一样。
    • 我相信我现在拥有它。我需要先将字符串编码为utf-8,然后将其编码为unquote_plus,然后再将其解码为utf-8,返回unicode。
    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 2017-05-13
    • 2016-11-29
    • 2018-06-19
    • 2020-05-06
    • 2011-01-28
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多