Python 3.0 urllib.parse错误"类型str不支持缓冲区API"

Eva*_*ark 23 python cgi urllib python-3.x

  File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__
    self.read_urlencoded()
  File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded
    self.strict_parsing):
  File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl
    pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
Run Code Online (Sandbox Code Playgroud)

任何人都可以指导我如何避免这种情况?我通过将数据输入到中来得到它cgi.Fieldstorage,我似乎无法以任何其他方式做到这一点.

bob*_*nce 28

urllib正在尝试:

b'a,b'.split(',')
Run Code Online (Sandbox Code Playgroud)

哪个不起作用.Py3k中的字节字符串和unicode字符串混合得比以前更加平滑 - 故意使编码问题尽快出错.

所以错误是不透明地告诉你'你不能将字节串传递给urllib.parse'.大概你正在做一个POST请求,其中表单编码的字符串作为内容体进入cgi; 内容正文仍然是一个字节字符串/流,所以它现在与新的urllib冲突.

所以,是的,它是cgi.py中的一个错误,是2to3转换的另一个受害者,没有为新的字符串模型正确修复.应该将传入的字节流转换为字符,然后再将它们传递给urllib.

我是否提到Python 3.0的库(尤其是与Web相关的库)仍然相当笨拙?:-)


Mar*_*ark 13

从python教程(http://www.python.org/doc/3.0/tutorial/stdlib.html)中有一个使用urlopen方法的示例.它引发了同样的错误.

for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
    if 'EST' in line or 'EDT' in line:  # look for Eastern Time
        print(line)
Run Code Online (Sandbox Code Playgroud)

您需要使用str函数将byte thingo转换为具有正确编码的字符串.如下:

for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
    lineStr = str( line, encoding='utf8' )
    if 'EST' in lineStr or 'EDT' in lineStr:  # look for Eastern Time
        print(lineStr)
Run Code Online (Sandbox Code Playgroud)

  • 提供适用于两个版本的python的解决方案将非常有趣. (3认同)