Problem: Trying to translate instructor's python 2 code to python 3
Specific Problem: Cannot access message field from the form in python 3
Instructor's Code Snippet From Udacity Full-Stack Foundations Course
def do_POST(self):
try:
self.send_response(301)
self.send_header('Content-type', 'text/html')
self.end_headers()
ctype, pdict = cgi.parse_header(
self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ""
output += "<html><body>"
output += " <h2> Okay, how about this: </h2>"
output += "<h1> %s </h1>" % messagecontent[0]
output += '''<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name="message" type="text" ><input type="submit" value="Submit"> </form>'''
output += "</body></html>"
self.wfile.write(output)
print output
except:
pass
After looking up documentation, github repositories, stackoverflow posts, and spending countless hours... I could not figure out how to pull the messages field in python 3 like fields.get('message').
My attempt
def do_POST(self):
try:
length = int(self.headers['Content-Length'])
print(self.headers['Content-Type'])
self.send_response(301)
self.send_header('Content-type', 'text/html')
self.end_headers()
post_data = parse_qs(self.rfile.read(length).decode('utf-8'))
self.wfile.write("Lorem Ipsum".encode("utf-8"))
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ''
output += '<html><body>'
output += '<h2> Okay, how about this: </h2>'
output += '<h1> %s </h1>' % messagecontent[0]
# You now have a dictionary of the post data
output += "<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name='message' type='text'><input type='submit' value='Submit'></form>"
output += '</html></body>'
self.wfile.write(output.encode('utf-8'))
except:
print('Error!')
My post_data variable is a dictionary but I cannot find a way to pull out the 'hi' message that I typed into the form. I am also not sure if this is the right way to go about pulling the data from the form.
>>> post_data
{' name': ['"message"\r\n\r\nhi\r\n------WebKitFormBoundarygm0MsepKJXVrBubX--\r\n']}