【问题标题】:Python's BaseHTTPServer returns junky responsesPython 的 BaseHTTPServer 返回垃圾响应
【发布时间】:2017-01-09 21:00:02
【问题描述】:

我使用 Python 的 BaseHTTPServer 并实现了以下非常简单的 BaseHTTPRequestHandler:

class WorkerHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.wfile.write('{"status" : "ready"}')
        self.send_response(200)

当我从网络浏览器运行 GET 查询时,只需转到 localhost:port,我就会得到以下响应:

{"status" : "ready"}HTTP/1.0 200 OK
Server: BaseHTTP/0.3 Python/2.7.12
Date: Mon, 09 Jan 2017 12:45:13 GMT

我只想要 JSON。如何让服务器不发送这些垃圾数据?

HTTP/1.0 200 OK
Server: BaseHTTP/0.3 Python/2.7.12
Date: Mon, 09 Jan 2017 12:45:13 GMT

【问题讨论】:

  • 1.对于大多数应用程序,最好避免使用BaseHTTPServer。考虑在 Django 或 Flask 等 Web 框架之上使用真正的 HTTP 服务器(如 Nginx 或 IIS),除非您有非常明确且令人信服的理由坚持使用BaseHTTPServer。 2. 这不是“垃圾数据”。它是 HTTP 响应的一部分。它只是乱序(并且,根据您的回答,乱序是因为您以错误的顺序调用事物)。

标签: python basehttpserver basehttprequesthandler


【解决方案1】:

终于成功自己修复了。与您分享:

class WorkerHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write('{"status" : "ready"}')

交换了send_responsewfile.write。在send_response之后还添加了end_headers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2014-12-04
    相关资源
    最近更新 更多