如何确保HTTPServer的请求处理程序确实写出了响应?
考虑如下代码示例,用来启动一个仅处理POST请求的HTTP服务器:
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class RequestHandler(BaseHTTPRequestHandler):
def accept_request(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
def fetch_content(self):
return json.loads(self.rfile.read(int(self.headers.get("Content-Length"))))
def do_POST(self):
if self.path.endswith("/whatever/endpoint"):
# Get body data
body_data = self.fetch_content()
# Accept request
self.accept_request()
# Do something with received data
# blablablabla....
# Generate the json response as a string
my_json_data_str = "{\"Key1\":\"value1\",\"key2\":\"value2\"}"
# Reply
self.wfile.write(my_json_data_str.encode()) # <=== HERE IS THE ISSUE
if __name__ == "__main__":
http_server = HTTPServer(('', 8080), RequestHandler)
http_server.serve_forever()
我遇到的问题是,发送请求的客户端似乎收到了空的响应。
我尝试打印 self.wfile.write() 的返回值,但它恰好与我想发送的字节数完全一致(正如预期)。因此我认为数据实际上已经发送。
我也尝试在之后调用 self.wfile.flush(),但行为仍然相同。
在同一台机器上托管的另一台服务器程序(用C++编写),使用同一个端口,相同的客户端能按预期得到响应,所以我猜问题并不出在客户端自身。
我的Python HTTP服务器到底出什么问题,导致数据在到达客户端之前就丢失?
服务器在Windows 11机器上运行,使用Python 3.13.13。
解决方案
问题在于客户端并不会自行推断内容长度。
我为 "Content-Length" 增加了头部,结果工作正常。
例如,我把 accept_request() 函数替换为:
def reply(self, response):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(response)))
self.end_headers()
return self.wfile.write(response)
并用以下方式发送我的响应:
self.reply(my_json_data_str.encode())
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。