urllib2 request with binary file as payload

Michiel Sikma michiel at thingmajig.org
Wed May 11 20:20:13 EDT 2011


Hi there,
I made a small script implementing a part of Youtube's API that allows
you to upload videos. It's pretty straightforward and uses urllib2.
The script was written for Python 2.6, but the server I'm going to use
it on only has 2.5 (and I can't update it right now, unfortunately).
It seems that one vital thing doesn't work in 2.5's urllib2:

--

data = open(video['filename'], 'rb')

opener = urllib2.build_opener(urllib2.HTTPHandler)
req = urllib2.Request(settings['upload_location'], data, {
	'Host': 'uploads.gdata.youtube.com',
	'Content-Type': video['type'],
	'Content-Length': '%d' % os.path.getsize(video['filename'])
})
req.get_method = lambda: 'PUT'
url = opener.open(req)

--

This works just fine on 2.6:
send: <open file 'file.mp4', mode 'rb' at 0x1005db580>
sendIng a read()able

However, on 2.5 it refuses:
Traceback (most recent call last):
  File "./pyup", line 119, in <module>
    main()
  File "./pyup", line 116, in main
    url = opener.open(req)
  File "/usr/lib/python2.5/urllib2.py", line 381, in open
    response = self._open(req, data)
  File "/usr/lib/python2.5/urllib2.py", line 399, in _open
    '_open', req)
  File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.5/urllib2.py", line 1107, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.5/urllib2.py", line 1079, in do_open
    h.request(req.get_method(), req.get_selector(), req.data, headers)
  File "/usr/lib/python2.5/httplib.py", line 866, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.5/httplib.py", line 892, in _send_request
    self.send(body)
  File "/usr/lib/python2.5/httplib.py", line 711, in send
    self.sock.sendall(str)
  File "<string>", line 1, in sendall
TypeError: sendall() argument 1 must be string or read-only buffer, not file

Is there any other way I can do this? I'm pretty new to Python so I'm
not sure how to proceed at this point.

Thanks!

Michiel Sikma
We Demand HTML

http://wedemandhtml.com/
michiel at wedemandhtml.com



More information about the Python-list mailing list