ria
ria

Reputation: 7508

How to POST a file in Python mechanize, but without any form?

How can I make POST request with a file in Python mechanize, but without any existing form, I just need to POST a file "out of the blue". There are some examples of file upload on stackoverflow but all relate to attaching a file in a form.

I just need to generate a POST request with headers like:

Content-Length: 218853
Content-Type: application/octet-stream
Cookie: some-cookie-data

And in the POST data just the contents of a file from disk.

Cookies in the browser session need to be preserved, and I need to read back and process the response, which will be some Content-Type text/plain; with some JSON.

Upvotes: 0

Views: 1295

Answers (2)

Michael Wilson
Michael Wilson

Reputation: 870

It just so happens I happened to have mechanize code open to do this.

  # Mechanize
  from mechanize import Browser, urlopen, Request

  # Submit it!
  image_file    = open(image_filename)
  image_data    = image_file.read()

  request       = Request(url, image_data, {'Content-Type': 'application/octet-stream'})

  response      = urlopen(request)

P.S. LOL, I realize I blogged about this a long time ago:

http://theremichaelwilson.wordpress.com/2011/03/26/posting-a-file-with-mechanize-and-python/

Upvotes: 0

tkone
tkone

Reputation: 22768

EDIT: You said you were looking for a mechanize example. I'm not a mechanize user, but it does support the entire urllib2 API. So this SO answer will be of assistance: Send file using POST from a Python script

When you create a post you're making an HTTP transaction as such:

POST /path/to/script HTTP/1.0
User-Agent: UserAgent/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 7 

hello=world

So you're always sending in a "form" since that's how the post request receives data.

So, what you'd want to do is figure out however the script you're POSTing to is expecting it's data (the name attribute of the form is usually the key necessary for the key=value paring) and then just create your post request.

Make sure you're a using the correct encoding (multipart mime) and you're calculating the correct Content-Length for the header.

Upvotes: 2

Related Questions