cgi.parse_multipart函数在Python 3中引发TypeError [英] cgi.parse_multipart function throws TypeError in Python 3
问题描述
我正在尝试通过Udacity的Full Stack Foundations课程进行练习。我从 BaseHTTPRequestHandler
的子类中有 do_POST
方法,基本上我想获取一个名为<$ c $的帖子值c>邮件以多部分形式提交,这是该方法的代码:
I'm trying to make an exercise from Udacity's Full Stack Foundations course. I have the do_POST
method inside my subclass from BaseHTTPRequestHandler
, basically I want to get a post value named message
submitted with a multipart form, this is the code for the method:
def do_POST(self):
try:
if self.path.endswith("/Hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ""
output += "<html><body>"
output += "<h2>Ok, how about this?</h2>"
output += "<h1>{}</h1>".format(messagecontent)
output += "<form method='POST' enctype='multipart/form-data' action='/Hello'>"
output += "<h2>What would you like to say?</h2>"
output += "<input name='message' type='text'/><br/><input type='submit' value='Submit'/>"
output += "</form></body></html>"
self.wfile.write(output.encode('utf-8'))
print(output)
return
except:
self.send_error(404, "{}".format(sys.exc_info()[0]))
print(sys.exc_info() )
问题在于 cgi.parse_multipart(self.rfile,pdict)
引发异常: TypeError:can 't concat bytes to str
,该课程的视频中提供了实现,但他们使用的是Python 2.7,而我使用的是python 3,我整个下午都在寻找解决方案,但我找不到有用的东西,从python 3的多部分表单中读取数据的正确方法是什么?
The problem is that the cgi.parse_multipart(self.rfile, pdict)
is throwing an exception: TypeError: can't concat bytes to str
, the implementation was provided in the videos for the course, but they're using Python 2.7 and I'm using python 3, I've looked for a solution all afternoon but I could not find anything useful, what would be the correct way to read data passed from a multipart form in python 3?
推荐答案
我在这里遇到的是解决与您同样的问题。
我找到了一个愚蠢的解决方案。
我只是使用编码选项将字典中的边界项从字符串转换为字节。
I've came across here to solve the same problem like you have. I found a silly solution for that. I just convert 'boundary' item in the dictionary from string to bytes with an encoding option.
ctype, pdict = cgi.parse_header(self.headers['content-type'])
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
就我而言,看来工作正常。
In my case, It seems work properly.
这篇关于cgi.parse_multipart函数在Python 3中引发TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!