我刚读了尼姆罗德姆提到的问题。一个答案提到了海报模块。
这个模块可以进行multipart/form-data编码,因此如果向您的项目添加另一个依赖项不是问题,我将使用poster模块。
这并不像它应该的那么简单。有一个代码片段漂浮在网上,我用它来编写代码,它起到了作用。你可能要根据自己的需要调整它。class RequestWithMethod(urllib2.Request):
def __init__(self, method, *args, **kwargs):
self._method = method
urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return self._method
class RestRequest(object):
def __init__(self, base_url):
self.base_url = base_url
def request(self, url, method, headers={"Accept" : "application/json"}, data=None, json_response=True):
request = RequestWithMethod(url='{0}{1}{2}'.format(self.base_url, root_url(), url),
method=method,
headers=headers)
if data != None:
data = urllib.urlencode(data)
response = urllib2.urlopen(request, data=data).read()
if json_response:
return from_json(response)
else:
return response
def GET(self, url, **kwargs):
return self.request(url, 'GET', **kwargs)
def POST(self, url, **kwargs):
return self.request(url, 'POST', **kwargs)
def POST_FILE(self, url, file, headers={"Accept" : "application/json"}, data={}, **kwargs):
content_type, body = encode_multipart_formdata(data, file)
headers['Content-type'] = content_type
headers['Content-length'] = str(len(body))
request = RequestWithMethod(url='{0}{1}{2}'.format(self.base_url, root_url(), url),
data=body,
method='POST',
headers=headers)
return from_json(urllib2.urlopen(request).read())
def PUT(self, url, **kwargs):
return self.request(url, 'PUT', **kwargs)
def DELETE(self, url, **kwargs):
return self.request(url, 'DELETE', **kwargs)
def encode_multipart_formdata(data, file):
boundary = ' ThIs_Is_tHe_bouNdaRY_$'
L = []
for key, value in data.items():
L.append(' ' + boundary)
L.append('Content-Disposition: form-data; name="{0}"'.format(key))
L.append('')
L.append(value)
key, filename, value = file
L.append(' ' + boundary)
L.append('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(key, filename))
content_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
L.append('Content-Type: {0}'.format(content_type))
L.append('')
L.append(value)
L.append(' ' + boundary + ' ')
L.append('')
body = '\r\n'.join(L)
content_type = 'multipart/form-data; boundary={0}'.format(boundary)
return content_type, body