蟒蛇:HTTP与unen codeD二进制数据PUT [英] python: HTTP PUT with unencoded binary data
问题描述
我不能为我的生活弄清楚如何与逐字二进制数据在Python 2.7的标准Python库执行HTTP PUT请求。
I cannot for the life of me figure out how to perform an HTTP PUT request with verbatim binary data in Python 2.7 with the standard Python libraries.
我想我可以用urllib2的做到这一点,但失败了,因为的 urllib2.Request
预计其数据应用程序/ x-WWW的形式urlen codeD
格式。我不想EN code中的二进制数据,我只是想逐字发送出去,包括
I thought I could do it with urllib2, but that fails because urllib2.Request
expects its data in application/x-www-form-urlencoded
format. I do not want to encode the binary data, I just want to transmit it verbatim, after the headers that include
Content-Type: application/octet-stream
Content-Length: (whatever my binary data length is)
这看起来很简单,但我一直转圈圈,似乎无法弄清楚如何。
This seems so simple, but I keep going round in circles and can't seem to figure out how.
我怎样才能做到这一点? (除了开辟原始二进制套接字和写入)
How can I do this? (aside from open up a raw binary socket and write to it)
推荐答案
我找到了我的问题。它似乎还有在 urllib2.Request 一些不起眼的行为code>
/ urllib2.urlopen ()
(至少在Python 2.7)
I found out my problem. It seems there is some obscure behavior in urllib2.Request
/ urllib2.urlopen()
(at least in Python 2.7)
的 urllib2.Request(网址,数据,标题)
构造似乎期待同类型在其URL和数据参数字符串。
The urllib2.Request(url, data, headers)
constructor seems to expect the same type of string in its url and data parameters.
我是从文件读取()
电话给数据参数的原始数据(这在Python 2.7返回时,就在一个'纯'字符串的形式),但我的网址是偶然的Uni code,因为我从返回的Uni code字符串的另一个函数的结果级联的URL的一部分。
I was giving the data parameter raw data from a file read()
call (which in Python 2.7 returns it in the form of a 'plain' string), but my url was accidentally Unicode because I concatenated a portion of the URL from the result of another function which returned Unicode strings.
而不是试图垂头丧气网址
从统一code - >普通字符串,它试图向上转型的数据
参数统一code,它给了我一个codeC错误。 (奇怪的是,这种情况发生在 urllib2.urlopen()
函数调用,而不是 urllib2.Request
构造函数)
Rather than trying to "downcast" url
from Unicode -> plain strings, it tried to "upcast" the data
parameter to Unicode, and it gave me a codec error. (oddly enough, this happens on the urllib2.urlopen()
function call, not the urllib2.Request
constructor)
当我改变了我的函数调用
When I changed my function call to
# headers contains `{'Content-Type': 'application/octet-stream'}`
r = urllib2.Request(url.encode('utf-8'), data, headers)
它工作得很好。
这篇关于蟒蛇:HTTP与unen codeD二进制数据PUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!