python问题中的UTF8

2024-03-28 11:41:19 发布

您现在位置:Python中文网/ 问答频道 /正文

嗯,我不是python中utf-8的粉丝;似乎不知道如何解决这个问题。如您所见,我已经在尝试对值进行B64编码,但是python似乎正在尝试首先将其从utf-8转换为ascii。。。在

一般来说,我尝试使用urllib2来发布包含UTF-8字符的表单数据。我想大体上它和How to send utf-8 content in a urllib2 request?是一样的,尽管没有有效的答案。我试图通过base64编码只发送一个字节字符串。在

Traceback (most recent call last):
  File "load.py", line 165, in <module>
    main()
  File "load.py", line 17, in main
    beers()
  File "load.py", line 157, in beers
    resp = send_post("http://localhost:9000/beers", beer)
  File "load.py", line 64, in send_post
    connection.request ('POST', req.get_selector(), *encode_multipart_data (data, files))
  File "load.py", line 49, in encode_multipart_data
    lines.extend (encode_field (name))
  File "load.py", line 34, in encode_field
    '', base64.b64encode(u"%s" % data[field_name]))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 53, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 7: ordinal not in range(128)

代码:

^{pr2}$

beer对象的json是(这是传递给encode_multipart_datadata):

    {
    "name"        : "Yuengling Oktoberfest",
    "brewer"      : "Yuengling Brewery",
    "description" : "America’s Oldest Brewery is proud to offer Yuengling Oktoberfest Beer. Copper in color, this medium bodied beer is the perfect blend of roasted malts with just the right amount of hops to capture a true representation of the style. Enjoy a Yuengling Oktoberfest Beer in celebration of the season, while supplies last!",
    "abv"         : 5.2, 
    "ibu"         : 26, 
    "type"        : "Lager",
    "subtype"     : "",
    "color"       : "",
    "seasonal"    : true,
    "servingTemp" : "Cold",
    "rating"      : 3,
    "inProduction": true  
    }

Tags: ofthetoinpysenddataline
1条回答
网友
1楼 · 发布于 2024-03-28 11:41:19

你不能用base64编码Unicode,只能编码字节字符串。在Python2.7中,为需要字节字符串的函数提供Unicode字符串会导致使用ascii编解码器隐式转换为字节字符串,从而导致您看到的错误:

>>> base64.b64encode(u'America\u2019s')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\base64.py", line 53, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 7: ordinal not in range(128)

因此,首先使用有效编码将其编码为字节字符串:

^{pr2}$

相关问题 更多 >