Tôi đang cố gắng thực hiện bài tập từ khóa Full Stack Foundations của Udacity. Tôi có phương pháp do_POST
bên trong lớp con của tôi từ BaseHTTPRequestHandler
, về cơ bản tôi muốn có được một giá trị sau tên message
nộp cùng với một hình thức nhiều phần dữ liệu, đây là mã cho phương pháp:Chức năng cgi.parse_multipart sẽ ném TypeError vào Python 3
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() )
Vấn đề là các cgi.parse_multipart(self.rfile, pdict)
được ném một ngoại lệ: TypeError: can't concat bytes to str
, việc triển khai được cung cấp trong video cho khóa học, nhưng họ đang sử dụng Python 2.7 và tôi đang sử dụng python 3, tôi đã tìm giải pháp tất cả vào buổi chiều nhưng tôi không thể tìm thấy bất kỳ điều gì hữu ích cách chính xác để đọc dữ liệu được truyền từ một biểu mẫu nhiều phần trong python 3?
này mang lại cho tôi một lỗi, 'đối tượng 'byte' không có thuộc tính 'readline' '. Làm thế nào để đối phó với điều này? –
@AmitBadhekaPykihStaff bạn có thể thử làm như sau 'từ io nhập khẩu BytesIO' và sau đó' cgi.parse_multipart (BytesIO (yourcontent), pdict) ' – CarlJ