How to manufacture a multipart/form-data POST?

556 views
Skip to first unread message

Peter Bengtsson

unread,
Jun 27, 2011, 12:13:31 PM6/27/11
to python-...@googlegroups.com
Trying to write a test that tests a POST form that uploads an image. I can't get it right. Nothing gets populated in self.request.files inside the `post(self)` request handler.

I'm wrapping the AsyncHTTPTestCase so I can do:

        full_url = self.get_url(url)
        request = HTTPRequest(full_url, follow_redirects=follow_redirects,
                              headers=headers, method=method, body=data)
        self.http_client.fetch(request, self.stop)
        return self.wait()

Is there a ready made tool or gist for making a multipart/form-data request into this without having to figure out the boundary stuff and the right \r\n paddings?

Bill Janssen

unread,
Jun 27, 2011, 1:21:24 PM6/27/11
to Tornado Web Server
It's atrocious that the standard httplib doesn't support this (see
http://bugs.python.org/issue3244). However, there's a good recipe for
doing this at http://code.activestate.com/recipes/146306/, which I've
used for years. It's also possible to do this using the
email.message.Message class, though you have to add the Content-
Disposition headers explicitly, something like this:

m = email.message.Message()
m.add_header("Content-Type", "multipart/form-data")
for (name, value_type, value) in items:
part = email.message.Message()
part.add_header("Content-Type", value_type)
part.add_header("Content-Disposition", 'form-data; name="%s"' %
name)
part.set_payload(value)
m.attach(part)
body = m.as_string()

Bill

Peter Bengtsson

unread,
Jun 28, 2011, 6:11:19 PM6/28/11
to python-...@googlegroups.com
That's awesome! It works.
Reply all
Reply to author
Forward
0 new messages