multipart/form-data类型的POST实体结构相对来说(常规的POST正文采用application/x-www-form-urlencoded格式)比较复杂,它常用于文件上传。
下面是一个multipart/form-data格式的POST实体示例
-----------------------------114782935826962 Content-Disposition: form-data; name="dv_deputy" e5471d92ebec3654ee6b90d131d296f4 -----------------------------114782935826962 Content-Disposition: form-data; name="form_id" submit_new_resume -----------------------------114782935826962 Content-Disposition: form-data; name="resumator-subdomain-value" app -----------------------------114782935826962 Content-Disposition: form-data; name="resumator-tags-value" -----------------------------114782935826962 Content-Disposition: form-data; name="resumator-job-value" 0 -----------------------------114782935826962 Content-Disposition: form-data; name="manual" true -----------------------------114782935826962 Content-Disposition: form-data; name="resumator-eeo_disability-value" 0 -----------------------------114782935826962-- 最后这里还有一个空行
封装代码如下:
# coding: utf-8 # util.py import os import mimetypes import mimetools def get_content_type(filepath): return mimetypes.guess_type(filepath)[0] or 'application/octet-stream' def encode_multipart_formdata(fields, files=[]): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filepath) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = mimetools.choose_boundary() CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filepath) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, os.path.basename(filepath))) L.append('Content-Type: %s' % get_content_type(filepath)) L.append('') L.append(open(filepath, 'rb').read()) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body
encode_multipart_formdata返回的content_type应设置为content-type头。body即为封装后的数据。
参考:http://code.activestate.com/recipes/146306/