python - 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()
解决方案
如果您查看 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 做了什么)。
推荐阅读
- python - 如何使用 XML 避免双重转义
- spring-boot - Logback - 为记录器/日志级别定义许多 Appender/Pattern
- python - ModuleNotFoundError:没有名为“bokeh.plotting.helpers”的模块与 bkcharts
- tensorflow2.0 - Universal Sentence Encoder 加载错误“错误:SavedModel 文件不存在于...”
- python - some_list=[a,b] 和 some_list=[a]+b 有什么区别?
- java - 解析文本文件,将其拆分为行,返回一个列表并映射到对象
- amazon-web-services - 无法使用 HTTP 连接到 AWS ec2 jupyter notebook --port 80?
- reactjs - 无法选中复选框以与 redux 做出反应
- javascript - 当输入项超过 2 位时,Array.prototype.sort() 失败
- ruby-on-rails - 对 Rails MVC 感到困惑:为什么视图可以调用模型方法?