2014-04-01 129 views
3

我想使用python製作一個HTTP服務器來託管我的網站。我已經實現了do_GET()方法,它工作正常,但是當我嘗試POST方法時,服務器沒有響應,直到我重新加載頁面。然後它醒來,完成POST,但意識到連接已經結束。之後,它爲GET方法提供服務(因爲我重新加載了頁面)並繼續正常運行。Python HTTP服務器對POST請求沒有響應

我在客戶端使用jQuery,但我也試過html窗體。即使我在另一個瀏覽器中打開該頁面也沒有改變,所以它必須是服務器端的例外。

下面是客戶端的javascript:

function Send() 
     { 
      jQuery.post("address", "Blah!", function (data) { 
       //get response 
       alert(data); 
      }); 
     } 

這裏是服務器端的代碼(我使用python 3.3.4):

class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler): 
    def do_POST(self): 
     print("Data: " + str(self.rfile.read(), "utf-8")) #show request 

     response = bytes("This is the response.", "utf-8") #create response 

     self.send_response(200) #create header 
     self.send_header("Content-Length", str(len(response))) 
     self.end_headers() 

     self.wfile.write(response) #send response 

這是從服務器日誌:

10.175.72.200 - - [01/Apr/2014 19:11:26] "GET/HTTP/1.1" 200 - 
Data: Blah! 
10.175.72.200 - - [01/Apr/2014 19:11:47] "POST /address HTTP/1.1" 200 - 
---------------------------------------- 
Exception happened during processing of request from ('10.175.72.200', 2237) 
Traceback (most recent call last): 
    File "C:\Python33\lib\socketserver.py", line 306, in _handle_request_noblock 
    self.process_request(request, client_address) 
    File "C:\Python33\lib\socketserver.py", line 332, in process_request 
    self.finish_request(request, client_address) 
    File "C:\Python33\lib\socketserver.py", line 345, in finish_request 
    self.RequestHandlerClass(request, client_address, self) 
    File "C:\Python33\lib\socketserver.py", line 666, in __init__ 
    self.handle() 
    File "C:\Python33\lib\http\server.py", line 400, in handle 
    self.handle_one_request() 
    File "C:\Python33\lib\http\server.py", line 388, in handle_one_request 
    method() 
    File "C:\Users\Jirek\Desktop\Server\server.py", line 45, in do_POST 
    self.wfile.write(response) #send response 
    File "C:\Python33\lib\socket.py", line 317, in write 
    return self._sock.send(b) 
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine 
---------------------------------------- 
10.175.72.200 - - [01/Apr/2014 19:11:47] "GET/HTTP/1.1" 200 - 

你可以看到,第一行是經典的GET請求。然後我從瀏覽器調用POST,直到重新加載才發生任何事情。此時服務器將寫入剩餘的日誌。

回答

5

問題解決!代碼載入收到的數據(位於do_POST())。我只需指定要讀取的數據量。

所以,只是不要使用rfile.read(),但rfile.read(numberOfBytes)。有多大POST信息會儲存在標題:numberOfBytes = int(self.headers["Content-Length"])

的修復方法:

def do_POST(self): 
    length = int(self.headers["Content-Length"]) 
    print("Data: " + str(self.rfile.read(length), "utf-8")) 

    response = bytes("This is the response.", "utf-8") #create response 

    self.send_response(200) #create header 
    self.send_header("Content-Length", str(len(response))) 
    self.end_headers() 

    self.wfile.write(response) #send response 
相關問題