我使用的是Python 3.6。
我正在尝试将JSON返回到一个post请求:
from http.server import HTTPServer, SimpleHTTPRequestHandler
from io import BytesIO
class TaroHttpHandler(SimpleHTTPRequestHandler):
def parse_url(self, path):
...
return path_component, query_components
def do_POST(self):
path_component, _ = self.parse_url(self.path)
if path_component == '/taro/three-cards/set-rating/':
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
self.send_header(keyword="Content-Type", value="application/json")
self.send_response(200) # 200 Ok is printed.
self.end_headers()
response = BytesIO()
response.write(b'{Rating: 1}')
response.write(body)
self.wfile.write(response.getvalue()) # Breakpoint
def run(server_class=HTTPServer,
handler_class=TaroHttpHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
run()
(Github:https://github.com/Kifsif/tmp.git)。
我发送了一个帖子请求:
curl -H "User-Agent: floor-9" -X POST http://localhost:8000/taro/three-cards/set-rating/
curl: (52) Empty reply from server
在服务器端,我有一个错误:
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 45300)
Traceback (most recent call last):
File "/usr/lib/python3.6/socketserver.py", line 320, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.6/socketserver.py", line 351, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.6/socketserver.py", line 724, in __init__
self.handle()
File "/usr/lib/python3.6/http/server.py", line 418, in handle
self.handle_one_request()
File "/usr/lib/python3.6/http/server.py", line 406, in handle_one_request
method()
File "/home/michael/Documents/taro/taro.py", line 71, in do_POST
content_length = int(self.headers['Content-Length'])
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
----------------------------------------
为什么会出现错误,以及如何应对?当我通过Postman程序发送投递请求时,content_length=165。在卷曲的情况下,self.headers['Content-Length']=无。我甚至添加了一个用户代理标头。但它仍然是"无"。
这应该会有所帮助。
在curl
命令中使用带有空字符串的-d
标志,这将向请求附加长度为0的数据,因此将添加一个内容长度标头。
curl -H "User-Agent: floor-9" -X POST http://localhost:8000/taro/three-cards/set-rating/ -d ""
处理try except
中的错误并使用400 Bad Request
进行响应可能是值得的