9

我有一个继承BaseHTTPRequestHandler并实现方法的 Python 类do_POST

我目前只成功响应整数状态,例如 200,在方法末尾使用以下命令:

self.send_response(200)

我也在尝试发送一些字符串作为响应的一部分。我该怎么做?

4

3 回答 3

18

至少在我的环境(Python 3.7)中我必须使用

self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json_str.encode(encoding='utf_8'))

否则将抛出此错误:TypeError: a bytes-like object is required, not 'str'

于 2019-02-25T16:09:42.363 回答
8

事实证明它非常简单,尽管没有太多示例。

只需使用:

self.wfile.write(YOUR_STRING_HERE)

专门针对json的情况:

import json
json_string = json.dumps(YOUR_DATA_STRUCTURE_TO_CONVERT_TO_JSON)
self.wfile.write(json_string)
于 2017-01-02T15:12:44.703 回答
2

这是一个老问题。不过,如果其他人可能想知道同样的问题,这是我的 2 美分。

如果你在做任何有用的事情,除了玩 python 之外,你应该开始寻找标准的 python 框架来处理 HTTP 服务器操作,比如 Django 或 Flask。

话虽如此,我用一个小存根作为我的传出请求的测试服务器,它应该回答你的问题。您可以通过修改设置任何状态代码、标头或响应正文:

#!/usr/bin/env python
# Reflects the requests with dummy responses from HTTP methods GET, POST, PUT, and DELETE
# Written by Tushar Dwivedi (2017)

import json
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from optparse import OptionParser

class RequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        request_path = self.path

        print("\n----- Request Start ----->\n")
        print("request_path :", request_path)
        print("self.headers :", self.headers)
        print("<----- Request End -----\n")

        self.send_response(200)
        self.send_header("Set-Cookie", "foo=bar")
        self.end_headers()
        self.wfile.write(json.dumps({'hello': 'world', 'received': 'ok'}))

    def do_POST(self):
        request_path = self.path

        # print("\n----- Request Start ----->\n")
        print("request_path : %s", request_path)

        request_headers = self.headers
        content_length = request_headers.getheaders('content-length')
        length = int(content_length[0]) if content_length else 0

        # print("length :", length)

        print("request_headers : %s" % request_headers)
        print("content : %s" % self.rfile.read(length))
        # print("<----- Request End -----\n")

        self.send_response(200)
        self.send_header("Set-Cookie", "foo=bar")
        self.end_headers()
        self.wfile.write(json.dumps({'hello': 'world', 'received': 'ok'}))

    do_PUT = do_POST
    do_DELETE = do_GET


def main():
    port = 8082
    print('Listening on localhost:%s' % port)
    server = HTTPServer(('', port), RequestHandler)
    server.serve_forever()


if __name__ == "__main__":
    parser = OptionParser()
    parser.usage = ("Creates an http-server that will echo out any GET or POST parameters, and respond with dummy data\n"
                    "Run:\n\n")
    (options, args) = parser.parse_args()

    main()

同样,即使你只是学习,甚至需要if else在上面添加 5-6 个 s 来做你正在做的事情,最好从头开始做,以避免将来大量返工。使用能够为您处理样板文件的框架。

于 2018-09-08T11:11:32.273 回答