如何使用urllib2在Python中发布tgz文件

时间:2015-06-15 11:07:56

标签: python rest post urllib2

我想将带有Python urllib2库的.tgz文件发送到后端服务器。由于某些许可问题,我无法使用请求。 stackoverflow上有一些文件上传示例,但都与在表单中附加文件有关。

我的代码如下,但不幸的是失败了:

stats["random"] = "data"

statsFile = "mydata.json"
headersFile = "header-data.txt"
tarFile = "body.tgz"

headers = {}
#Some custom headers
headers["X-confidential"] = "Confidential"
headers["X-version"] = "2"
headers["Content-Type"]  = "application/x-gtar"

#Create the json and txt files
    with open(statsFile, 'w') as a, open(headersFile, 'w') as b:
        json.dump(stats, a, indent=4)
        for k,v in headers.items():
            b.write(k+":"+v+"\n")

#Create a compressed file to send
tar = tarfile.open(tarFile, 'w:gz' )
    for name in [statsFile,headersFile]:
        tar.add(name)
    tar.close()

#Read the binary data from the file
with open(tarFile, 'rb') as f:
    content = f.read()

url = "http://www.myurl.com"
req = urllib2.Request(url, data=content, headers=headers)
response = urllib2.urlopen(req, timeout=timeout)

如果我使用请求,它就像一个魅力:

r = requests.post(url, files={tarFile: open(tarFile, 'rb')}, headers=headers)

我基本上需要urllib2的上述等价物。有人可能知道吗?我也检查了文档,但我无法使其工作。我错过了什么?

谢谢!

0 个答案:

没有答案