forms - cgi.parse_multipart function throws TypeError in Python 3 -
i'm trying make exercise udacity's full stack foundations course. have do_post
method inside subclass basehttprequesthandler
, want post value named message
submitted multipart form, code 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 this?</h2>" output += "<h1>{}</h1>".format(messagecontent) output += "<form method='post' enctype='multipart/form-data' action='/hello'>" output += "<h2>what 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() )
the problem cgi.parse_multipart(self.rfile, pdict)
throwing exception: typeerror: can't concat bytes str
, implementation provided in videos course, they're using python 2.7 , i'm using python 3, i've looked solution afternoon not find useful, correct way read data passed multipart form in python 3?
i've came across here solve same problem have. found silly solution that. convert 'boundary' item in dictionary string bytes 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 case, seems work properly.
Comments
Post a Comment