POST data should be bytes or an iterable of bytes. It cannot be str.

作者:小鱼的互联网观察 发布时间:July 16, 2011 分类:技术

 

I just updated from python 3.1 to python 3.2 (formatted HD) and one of my scripts stopped working. It gives me the error in the title.

I would fix it myself but I don't even know what an iterable of bytes is lol. I tried typecasting bytes(data) but that didn't work either. TypeError: string argument without an encoding


url = "http://site.com/index.php?app=core&module=global&section=login&do=process"
values = {"username" : USERNAME, 
          "password" : PASSWORD}
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
urllib.request.urlopen(req)




It crashes at the last line.

Works in 3.1, but not 3.2

Thanks in advance.

 

======================================

Answer

 

 

You did basically correct in trying to convert the string into bytes, but you did it the wrong way. Python doesn't have typecasting (so what you did was not typecasting).

The way to do it is to encode the text data into bytes data, which you do with the encode function:

<code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 14px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: rgb(238, 238, 238); font-family: Consolas, Menlo, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', monospace, serif; background-position: initial initial; background-repeat: initial initial; ">binary_data = data.encode('encoding')</code>

What 'encoding' should be depends. You should probably use 'ascii' here. If you have characters that isn't ASCII, then you need to use another encoding, typically 'utf8', but then you also need to tell the receiving webserver that it is UTF-8. It might also not want UTF8, but then you have to ask it, and it's getting complicated. :-)

 

标签: POST data should be bytes or an iterable of bytes. It cannot be str.

互联网观察
POST data should be bytes or an iterable of bytes. It cannot be str.
本文地址:https://tianmeng.org/archives/271/

相关文章

  • 无相关文章
文档信息

当前暂无评论 »

网站地图 京ICP证030173号