我一直在尝试在Python 3.6中创建一个基本的多部分表单。 do_GET方法运行正常,但do_POST方法仍然失败。
当我在Chrome中提交表单时,它说 localhost没有发送任何数据。 ERR_EMPTY_RESPONSE ,但是当我检查开发者控制台中的“网络”选项卡时,我可以看到表单值。
代码似乎与Python 2.7完美配合。我不确定代码中出错的地方。
这是我写的代码:
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
class WebServerHandle(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith("/new"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
output = ""
output += "<html><head><style>body {font-family: Helvetica, Arial; color: #333}</style></head>"
output += "<body><h2>Add new Restaurant</h2>"
output += "<form method='POST' enctype='multipart/form-data' action='/new'>"
output += "<input name='newRestaurantName' type='text' placeholder='New Restaurant Name'> "
output += "<input type='submit' value='Add Restaurant'>"
output += "</form></html></body>"
self.wfile.write(bytes(output, "utf-8"))
return
if self.path.endswith("/restaurant"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
output = ""
output += "<html><head><style>body {font-family: Helvetica, Arial; color: #333}</style></head>"
output += "<body><h3>Restaurant name added successfully!</h3>"
output += "</html></body>"
self.wfile.write(bytes(output, "utf-8"))
return
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def do_POST(self):
try:
if self.path.endswith("/new"):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
restaurant_name = fields.get('newRestaurantName')
print("Restaurant name is ", restaurant_name)
self.send_response(301)
self.send_header('Content-type', 'text/html')
self.send_header('Location', '/restaurant')
self.end_headers()
except:
print("Something went wrong, inside exception..")
def main():
try:
server = HTTPServer(('', 8080), WebServerHandle)
print("Starting web server on the port 8080..")
server.serve_forever()
except KeyboardInterrupt:
print('^C entered. Shutting down the server..')
server.socket.close()
if __name__ == '__main__':
main()
答案 0 :(得分:2)
进行了更改以解码表单中的字段值。
将self.headers.getheader('content-type')
方法更改为
self.headers.('content-type')
。
然后在此之后添加以下行,以解码pdict
值:
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
,
然后通过从字节转换为字符串来打印字段值,我将print
行更改为
print("Restaurant name is ", restaurant_name[0].decode("utf-8"))
。
所以最终的代码如下:
def do_POST(self):
try:
if self.path.endswith("/new"):
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)
print("Fields value is", fields)
restaurant_name = fields.get('newRestaurantName')
print("Restaurant name is ", restaurant_name[0].decode("utf-8"))
self.send_response(301)
self.send_header('Content-type', 'text/html')
self.send_header('Location', '/restaurant')
self.end_headers()
except:
print("Inside the exception block")
答案 1 :(得分:0)
Python 3.8
def do_POST(self):
try:
if self.path.endswith("/new"):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
pdict['CONTENT-LENGTH'] = int(self.headers['Content-Length'])
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
print("Fields value is", fields)
restaurant_name = fields.get('newRestaurantName')
print("Restaurant name is ", restaurant_name[0].decode("utf-8"))
self.send_response(301)
self.send_header('Content-type', 'text/html')
self.send_header('Location', '/restaurant')
self.end_headers()
except:
print("Inside the exception block")