我正在使用Python3.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()(地理信息中心: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'
----------------------------------------错误存在的原因以及如何处理?当我通过邮递员程序发送邮件请求时,content_length = 165。在卷曲的情况下,自标头‘内容-长度’=无。我甚至添加了一个用户代理头。但还是没有。
发布于 2020-05-05 10:36:28
This应该能帮上忙。
在您的-d命令中使用带有和空字符串的curl标志,这将将0长度的数据附加到请求中,从而添加一个内容长度标题。
curl -H "User-Agent: floor-9" -X POST http://localhost:8000/taro/three-cards/set-rating/ -d ""但是,处理try except中的错误并使用400 Bad Request响应可能是值得的。
https://stackoverflow.com/questions/61610936
复制相似问题