TypeError: POST 数据应该是字节或可迭代的字节.它不能是 str [英] TypeError: POST data should be bytes or an iterable of bytes. It cannot be str

查看:65
本文介绍了TypeError: POST 数据应该是字节或可迭代的字节.它不能是 str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从 python 3.1 更新到 python 3.2(格式化的高清),我的一个脚本停止工作.它给了我标题中的错误.

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://example.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)

它在最后一行崩溃.

适用于 3.1,但不适用于 3.2

Works in 3.1, but not 3.2

推荐答案

您在尝试将字符串转换为字节时基本上是正确的,但是您以错误的方式进行了操作.Python 没有类型转换(所以你所做的不是类型转换).

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).

这样做的方法是将文本数据编码为字节数据,您可以使用 encode 函数执行此操作:

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

binary_data = data.encode('encoding')

什么编码"应该取决于.您可能应该在这里使用ascii".如果您的字符不是 ASCII,那么您需要使用另一种编码,通常是utf8",但您还需要告诉接收网络服务器它是 UTF-8.它也可能不想要 UTF8,但是你必须问它,而且它变得复杂了.:-)

What 'encoding' should be depends. You should probably use 'ascii' here. If you have characters that aren'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. :-)

这篇关于TypeError: POST 数据应该是字节或可迭代的字节.它不能是 str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆