00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037 """
00038 Utilities for loading attachment into WG Inventory System. Used in
00039 wg_invent_client package only. No external code API
00040 """
00041
00042 import urllib2
00043 import mimetypes
00044 import mimetools
00045
00046
00047
00048 def _encode_multipart_formdata(fields, files, BOUNDARY = '-----'+mimetools.choose_boundary()+'-----'):
00049 """
00050 Encodes fields and files for uploading.
00051 fields is a sequence of (name, value) elements for regular form fields - or a dictionary.
00052 files is a sequence of (name, filename, value) elements for data to be uploaded as files.
00053 Return (content_type, body) ready for urllib2.Request instance
00054 You can optionally pass in a boundary string to use or we'll let mimetools provide one.
00055 """
00056
00057 CRLF = '\r\n'
00058
00059 L = []
00060
00061 if isinstance(fields, dict):
00062 fields = fields.items()
00063
00064 for (key, value) in fields:
00065 L.append('--' + BOUNDARY)
00066 L.append('Content-Disposition: form-data; name="%s"' % key)
00067 L.append('')
00068 L.append(value)
00069
00070 for (key, filename, value) in files:
00071
00072 encoded = value
00073 filetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
00074 L.append('--' + BOUNDARY)
00075 L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
00076 L.append('Content-Length: %s' % len(encoded))
00077 L.append('Content-Type: %s' % filetype)
00078 L.append('Content-Transfer-Encoding: binary')
00079 L.append('')
00080 L.append(encoded)
00081
00082 L.append('--' + BOUNDARY + '--')
00083 L.append('')
00084 body = CRLF.join([str(l) for l in L])
00085
00086 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
00087
00088 return content_type, body
00089
00090 def build_request(theurl, fields, files, txheaders=None):
00091 content_type, body = _encode_multipart_formdata(fields, files)
00092 if not txheaders: txheaders = {}
00093 txheaders['Content-type'] = content_type
00094 txheaders['Content-length'] = str(len(body))
00095 return urllib2.Request(theurl, body, txheaders)