1 #http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
2 # Submitter: Wade Leftwich
4 # according to http://aspn.activestate.com/ASPN/Cookbook/Python
5 # "Except where otherwise noted, recipes in the Python Cookbook are published under the Python license ."
6 # This recipe is covered under the Python license: http://www.python.org/license
8 import httplib
, mimetypes
, urllib2
9 from socket
import error
, herror
, gaierror
, timeout
11 def link_exists(host
, selector
):
13 Check to see if the given host exists and is reachable
16 site
= urllib2
.urlopen("http://" + host
+ selector
)
18 except urllib2
.URLError
, e
:
19 print "FAIL: graph server does not resolve"
20 print "FAIL: " + str(e
.reason
)
24 def post_multipart(host
, selector
, fields
, files
):
26 Post fields and files to an http host as multipart/form-data.
27 fields is a sequence of (name, value) elements for regular form fields.
28 files is a sequence of (name, filename, value) elements for data to be uploaded as files
29 Return the server's response page.
32 content_type
, body
= encode_multipart_formdata(fields
, files
)
33 h
= httplib
.HTTP(host
)
34 h
.putrequest('POST', selector
)
35 h
.putheader('content-type', content_type
)
36 h
.putheader('content-length', str(len(body
)))
39 errcode
, errmsg
, headers
= h
.getreply()
41 except (httplib
.HTTPException
, error
, herror
, gaierror
, timeout
), e
:
42 print "FAIL: graph server unreachable"
43 print "FAIL: " + str(e
)
46 print "FAIL: graph server unreachable"
49 def encode_multipart_formdata(fields
, files
):
51 fields is a sequence of (name, value) elements for regular form fields.
52 files is a sequence of (name, filename, value) elements for data to be uploaded as files
53 Return (content_type, body) ready for httplib.HTTP instance
55 BOUNDARY
= '----------ThIs_Is_tHe_bouNdaRY_$'
58 for (key
, value
) in fields
:
59 L
.append('--' + BOUNDARY
)
60 L
.append('Content-Disposition: form-data; name="%s"' % key
)
63 for (key
, filename
, value
) in files
:
64 L
.append('--' + BOUNDARY
)
65 L
.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key
, filename
))
66 L
.append('Content-Type: %s' % get_content_type(filename
))
69 L
.append('--' + BOUNDARY
+ '--')
72 content_type
= 'multipart/form-data; boundary=%s' % BOUNDARY
73 return content_type
, body
75 def get_content_type(filename
):
76 return mimetypes
.guess_type(filename
)[0] or 'application/octet-stream'