首页 > 解决方案 > python3 http.server 响应无效(Postman 和其他工具)

问题描述

我正在使用基本的 python3 库 http 并使用服务器模块设置测试服务器。

测试我的服务器,我设法在终端中使用 curl 正确获取并查看响应:

$ curl -H "Content-Type: application/json" -X GET "http://localhost:8080/health"                 
{"health": "ok"}HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.7.3
Date: Sun, 12 May 2019 19:52:21 GMT
Content-type: application/json

但是,如果我尝试使用 Postman 之类的工具提出请求。有了这个,我收到Could not get any response错误消息(请求确实到达服务器并被处理,我可以在服务器的日志记录中看到)。

是否有一种特定的方式来格式化我目前没有看到的回复?我就是这样做的:

    def _prepare_response(self):
        self._response_body({'health': 'ok'})
        self.send_response(200)
        self.send_header('Content-type','application/json')
        self.end_headers()

标签: pythonpython-3.xpostmanartillery

解决方案


如果您查看 curl 输出,这没有任何意义:“正文”甚至发生在状态行发送之前。

您应该在标头之后发送响应正文,而不是之前。这意味着您必须首先发送响应行,然后发送标头,然后结束标头,然后才wfile使用正文内容写入。所以代码应该是这样的:

 def _prepare_response(self):
        self.send_response(200)
        self.send_header('Content-type','application/json')
        self.end_headers()
        # move what I guess is a helper to after the headers
        self._response_body({'health': 'ok'})

而且您可能想确保正确地对 dict 进行 json 序列化,而不是将其传递给 str 并希望它与 JSON 兼容(我不知道 _response_body 做了什么)。


推荐阅读