~ubuntu-branches/ubuntu/karmic/pypy/karmic

« back to all changes in this revision

Viewing changes to py/test/web/post_multipart.py

  • Committer: Bazaar Package Importer
  • Author(s): Alexandre Fayolle
  • Date: 2007-04-13 09:33:09 UTC
  • Revision ID: james.westby@ubuntu.com-20070413093309-yoojh4jcoocu2krz
Tags: upstream-1.0.0
ImportĀ upstreamĀ versionĀ 1.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import httplib, mimetypes
 
2
 
 
3
"""Copied from the cookbook 
 
4
 
 
5
    see ActiveState's ASPN 
 
6
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
 
7
"""
 
8
 
 
9
def post_multipart(host, selector, fields, files):
 
10
    """
 
11
    Post fields and files to an http host as multipart/form-data.
 
12
    fields is a sequence of (name, value) elements for regular form fields.
 
13
    files is a sequence of (name, filename, value) elements for data to be 
 
14
    uploaded as files
 
15
 
 
16
    Return the server's response page.
 
17
    """
 
18
    content_type, body = encode_multipart_formdata(fields, files)
 
19
    h = httplib.HTTP(host)
 
20
    h.putrequest('POST', selector)
 
21
    h.putheader('content-type', content_type)
 
22
    h.putheader('content-length', str(len(body)))
 
23
    h.endheaders()
 
24
    h.send(body)
 
25
    errcode, errmsg, headers = h.getreply()
 
26
    return h.file.read()
 
27
 
 
28
def encode_multipart_formdata(fields, files):
 
29
    """
 
30
    fields is a sequence of (name, value) elements for regular form fields.
 
31
    files is a sequence of (name, filename, value) elements for data to be 
 
32
    uploaded as files
 
33
    
 
34
    Return (content_type, body) ready for httplib.HTTP instance
 
35
    """
 
36
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
 
37
    CRLF = '\r\n'
 
38
    L = []
 
39
    for (key, value) in fields:
 
40
        L.append('--' + BOUNDARY)
 
41
        L.append('Content-Disposition: form-data; name="%s"' % key)
 
42
        L.append('')
 
43
        L.append(value)
 
44
    for (key, filename, value) in files:
 
45
        L.append('--' + BOUNDARY)
 
46
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % 
 
47
                        (key, filename))
 
48
        L.append('Content-Type: %s' % get_content_type(filename))
 
49
        L.append('')
 
50
        L.append(value)
 
51
    L.append('--' + BOUNDARY + '--')
 
52
    L.append('')
 
53
    body = CRLF.join(L)
 
54
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
 
55
    return content_type, body
 
56
 
 
57
def get_content_type(filename):
 
58
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'