Python HTTP服务器在POST请求时没有响应

时间:2014-04-01 18:26:52

标签: python post httpserver

我想使用python创建一个HTTP服务器来托管我的网站。我已经实现了do_GET()方法并且它工作正常,但是当我尝试POST方法时,服务器在我重新加载页面之前没有响应。然后它醒来,tring完成POST,但意识到连接已经结束。之后,它提供GET方法(因为我重新加载页面)并继续正常运行。

我在客户端使用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,直到重新加载才会发生任何事情。此时,服务器会写入剩余的日志。

1 个答案:

答案 0 :(得分:8)

问题解决了!它位于代码加载接收数据的行中(在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