How to POST a tgz file in Python using urllib2

1.1k views Asked by At

I would like to POST a .tgz file with the Python urllib2 library to a backend server. I can't use requests due to some licensing issues. There are some examples of file upload on stackoverflow but all relate to attaching a file in a form.

My code is the following but it unfortunately fails:

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)

If I use requests, it works like a charm:

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

I essentially need the equivalent of the above for urllib2. Does anybody maybe know it? I have checked the docs as well but I was not able to make it work..What am I missing?

Thanks!

0

There are 0 answers