urllib2 request with binary file as payload

John Machin sjmachin at lexicon.net
Wed May 11 20:57:31 EDT 2011


On Thu, May 12, 2011 10:20 am, Michiel Sikma wrote:
> 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):
[snip]
> TypeError: sendall() argument 1 must be string or read-only buffer, not
> file

I don't use this stuff, just curious. But I can read docs. Quoting from
the 2.6.6 docs:

"""
class urllib2.Request(url[, data][, headers][, origin_req_host][,
unverifiable])
This class is an abstraction of a URL request.

url should be a string containing a valid URL.

data may be a string specifying additional data to send to the server, or
None if no such data is needed. Currently HTTP requests are the only ones
that use data; the HTTP request will be a POST instead of a GET when the
data parameter is provided. data should be a buffer in the standard
application/x-www-form-urlencoded format. The urllib.urlencode() function
takes a mapping or sequence of 2-tuples and returns a string in this
format.
"""

2.6 is expecting a string, according to the above. No mention of file.
Moreover it expects the data to be urlencoded. 2.7.1 docs say the same
thing. Are you sure you have shown the code that worked with 2.6?





More information about the Python-list mailing list