【发布时间】:2015-01-21 20:06:27
【问题描述】:
我目前想在Python3中使用下面这段代码,但是发现mimetools.choose_boundary这个函数被弃用了,如何修改代码使其生效?
import re
from urllib.request import urlopen, Request
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
【问题讨论】:
-
似乎该功能已被删除而没有直接替换。就个人而言,我只想在您的代码中包含
email.generator模块的_make_boundary()函数的副本。
标签: python python-3.x httprequest mime multipartform-data