2017-03-09 24 views
0

我一直試圖在Python 3.6中創建一個基本的多部分表單。 do_GET方法工作正常,但do_POST方法保持失敗。do_POST方法在Python 3.6中失敗

當我在Chrome中提交表單時,它說本地主機沒有發送任何數據。 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

如果您刪除在'do_POST'方法'嘗試/ except',你會看到,這是一樣的http://stackoverflow.com/questions/31486618/cgi-parse-multipart-function-throws-typeerror-in-python-3 – snakecharmerb

+0

[cgi.parse \ _multipart函數在Python 3中引發TypeError]的可能重複(http://stackoverflow.com/questions/ 31486618/cgi-parse-multipart-function-throws-typeerror-in-python-3) – snakecharmerb

+0

@snakecharmerb代碼直接似乎沒有工作,但我需要將字段值解碼爲'utf-8'獲取字段值,然後使用try catch塊工作。 – starlight

回答

1

進行了更改解碼從表單字段值。

改變了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")