473,624 Members | 2,165 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

multipart/form-data in an HTTP client

I'm writing some code to upload photos to Flickr. The Photo Upload API
requires documents be POSTed via a multipart/form-data request. I was
surprised to learn that Python 2.3's HTTP clients don't support this
form of POSTs. There is support in cgi.py, for servers.

There are some implementations of multipart/form-data on ASPN:
http://aspn.activestate.com/ASPN/Coo.../Recipe/146306
urllib2_file seems to meet my needs, but I'm not wild about how it's
implemented. Is there some other recommended way to do
multipart/form-data uploads with HTTP in Python?
References:
http://www.flickr.com/services/api/
http://aspn.activestate.com/ASPN/Coo.../Recipe/146306
http://www.faqs.org/rfcs/rfc1867.html
Jul 18 '05 #1
5 5372
On Wed, 01 Sep 2004 14:52:33 GMT, Nelson Minar <ne****@monkey. org> wrote:
There are some implementations of multipart/form-data on ASPN:
http://aspn.activestate.com/ASPN/Coo.../Recipe/146306
urllib2_file seems to meet my needs, but I'm not wild about how it's
implemented. Is there some other recommended way to do
multipart/form-data uploads with HTTP in Python?


I like ClientForm. I hope one day it or something like it will be in the stdlib.
Jul 18 '05 #2
Nelson Minar <ne****@monkey. org> writes:
I'm writing some code to upload photos to Flickr. The Photo Upload API
requires documents be POSTed via a multipart/form-data request. I was
surprised to learn that Python 2.3's HTTP clients don't support this
form of POSTs. There is support in cgi.py, for servers.
"Not supported" is an exaggeration, perhaps: there isn't special
support to make it especially easy, true, but neither is there
anything about urllib2 that makes it harder than it should be given
the level of the interface exposed: you just have to add the right
HTTP headers and HTTP request body data.

There are some implementations of multipart/form-data on ASPN:
http://aspn.activestate.com/ASPN/Coo.../Recipe/146306
urllib2_file seems to meet my needs, but I'm not wild about how it's
implemented.


What's wrong with that implementation? Looks reasonable to me, though
it seems to have a hack to work around bad servers that is different to
the one I have in my own code. I can well believe that both hacks are
required to work with as many servers as possible :-(
John
Jul 18 '05 #3
Nelson Minar wrote:
I'm writing some code to upload photos to Flickr. The Photo Upload API
requires documents be POSTed via a multipart/form-data request. I was
surprised to learn that Python 2.3's HTTP clients don't support this
form of POSTs. There is support in cgi.py, for servers.

There are some implementations of multipart/form-data on ASPN:
http://aspn.activestate.com/ASPN/Coo.../Recipe/146306
urllib2_file seems to meet my needs, but I'm not wild about how it's
implemented. Is there some other recommended way to do
multipart/form-data uploads with HTTP in Python?


I've been using something closely modelled on that Cookbook recipe,
without any real problems. (I've updated it to use HTTP[S]Connection()
and return the response object, and in my case I'm connecting to an
HTTPS server, but these are trivial modifications.)

I, too, was surprised that the existing Python libraries don't directly
support multipart/form-data already, and I hope that this gets added in
soon.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #4
Jeff Shannon <je**@ccvcorp.c om> writes:
[...]
I've been using something closely modelled on that Cookbook recipe,
without any real problems. (I've updated it to use
HTTP[S]Connection() and return the response object, and in my case I'm
connecting to an HTTPS server, but these are trivial modifications.)

I, too, was surprised that the existing Python libraries don't
directly support multipart/form-data already, and I hope that this
gets added in soon.

[...]

Have you published your function? If not, please do.

Several people would like to see such a function in 2.5 (including
me), and your function sounds a good candidate. Maybe a little
polishing is required, but don't let that stop you: if you don't get
time to do that polishing, this is a rare occasion when somebody else
is likely to push it the small additional distance it would need to go
in order to get into the Python stdlib!
John
Jul 18 '05 #5
John J. Lee wrote:
Jeff Shannon <je**@ccvcorp.c om> writes:
[...]

I've been using something closely modelled on that Cookbook recipe,
without any real problems. (I've updated it to use
HTTP[S]Connection() and return the response object, and in my case I'm
connecting to an HTTPS server, but these are trivial modifications.)

[...]

Have you published your function? If not, please do.


Here it is, for what it's worth. (Hopefully my mailer won't mangle the
indentation...) As I noted, the differences between this and the
Cookbook recipe are minimal -- I literally copied the recipe into my
editor and made a few changes.

If I were going to put further effort into polishing it for library use
(which I probably won't have much opportunity to do), I'd make at least
two changes. One would be to set it up to select between HTTP and
HTTPS. (It currently tries to determine the protocol from the hostname
string, but does nothing with that information.) The other would be to
enable the file-subpart to add a Content-type header. (This is
irrelevant for my particular application, as the form(s) I'm uploading
to don't care.)

In case it matters to anyone, inasmuch as this code is nearly identical
to the published recipe, my changes can be considered to be under the
same license as the original recipe. If someone feels like using this
in any way, feel free.

Jeff Shannon
Technician/Programmer
Credit International
#! /usr/bin/python

import httplib

def post_multipart( host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files.
Return an appropriate httplib.HTTPRes ponse object.
"""
content_type, body = encode_multipar t_formdata(fiel ds, files)
protocol = host.split(':')[0]
h = httplib.HTTPSCo nnection(host)
h.putrequest('P OST', selector)
h.putheader('co ntent-type', content_type)
h.putheader('co ntent-length', str(len(body)))
h.endheaders()
h.send(body)
response = h.getresponse()
return response

def encode_multipar t_formdata(fiel ds, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files.
Return (content_type, body) ready for httplib.HTTPCon nection instance
"""
BOUNDARY = '----------ThIs_Is_tHe_bou NdaRY_---$---'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Conte nt-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Conte nt-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

34
4441
by: Niels Berkers | last post by:
Hi, i'd like to host my web pages using multiparts to reduce the number of hits on the server. i know this isn't a real PHP subject, but i'll try it anyway. i've been searching the web for solutions and examples with no succes. does anybody know a good starting point hints / tips are also welcome Regards
6
2925
by: LRW | last post by:
Because I've had recipients of our newsletter tell us they can't (or won't) receive HTML e-mail, I found out how to make an e-mail that sends both HTML and a plaintext version in a multipart message. Problem is, while the HTML version shows up fine in HTML enabled clients like Outlook, in plaintext clients it either shows nothing in the body or just an attachment link to the message source code. I've tried different encodings and bits...
2
3192
by: Damien | last post by:
Hi to all, After hours of attempts and "googling", I'm still pulling my hair off my head when I try to send multipart html emails. It "works" on PCs with Outlook when I juste send a single "related" mail: one part for the HTML body, and several for the images. However, the images do not show on a Mac. I also wanted to have an "alternate", plain text message. I've tried the method described by Zend and PHPBuilder, but no luck...
4
2982
by: Hunter Peress | last post by:
I have been unable to write a script that can do (and receieve) a multipart form upload. Also, it seems that there really are differences between python's implementation and else's. Can someone please prove me wrong with a script that works with itself AND with example 18-2 from php: http://www.php.net/manual/en/features.file-upload.php __________________________________
4
2808
by: John Fereira | last post by:
So, one of the limitations of multipart-form handling is that when an <input type="file" ..> tag is used it will bring up a window which allows a user to select a file for upload but won't allow the user to select multiple files. As you may know, the tag produces a text input field with an adjacent button for selecting a file from the local file system. As I would like to be able to allow the user to upload an arbitrary number of files...
3
2923
by: Li Zhang | last post by:
I know I can use controlName.Value to retrieve the form fields value if I am in that page. But if I am out of the page, for example I am in a HttpModule, I want to retrieve a hidden filed value, Is that possible? if so how? Thanks!
1
936
by: Juan Dent | last post by:
Hi, I am naming all my assemblies in a multipart format, e.g.: Company.Project.Component.dll This has worked perfectly with C# assemblies. The problem arises with C++ native COM servers because when I try to regsvr32 them they don't get registered.
2
6302
by: madmak | last post by:
Hi, I am a noob with PHP and need some asistance regarding PHP and lotus notes. I am trying to create a multipart message in PHP to send mail via lotus notes. Here is the code snippet. <?php ---some code here -- $session_notes = new COM("Lotus.NotesSession"); $session_notes->Initialize("<password>");
6
10554
by: fnoppie | last post by:
Hi, I am near to desperation as I have a million things to get a solution for my problem. I have to post a multipart message to a url that consists of a xml file and an binary file (pdf). Seperately the posting words fine but when I want to create one multipart message with both then things go wrong. The binary file is converted and of datatype byte() The xml file is just a string.
1
1209
by: Gabriel Genellina | last post by:
En Fri, 29 Aug 2008 14:41:53 -0300, Ron Brennan <brennan.ron@gmail.com> escribi�: What is a "multipart"? I know MIME multipart messages but they don't seem to apply here... From your other posts I think you're talking about a dictionary mapping each key to a list of values. So the values are contained inside a list. It doesn't matter *where* you store that list, or *how* you get access to it. You have a list of values
0
8234
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8172
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8620
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7158
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5563
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2605
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1482
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.