我在自己的线程上运行一个 http 服务器,并使用以下代码发出 PUT 请求。
服务器端:
thread = threading.Thread(target=run, args=[self.__infoPort])
thread.daemon = True
thread.start()
class V6Server(HTTPServer):
address_family = socket.AF_INET6
def run(port):
try:
server = V6Server(('::', port), CustomHandler)
server.serve_forever()
except Exception:
logging.error("Could not establish or maintain HTTP server")
class CustomHandler(SimpleHTTPRequestHandler):
def do_PUT(self):
secureNetworkFile = open(self.path, "r+")
secureNetworkJson = json.load(secureNetworkFile)
requestBody = self.rfile.read()
requestBodyJson = json.loads(requestBody)
secureNetworkJson["id"] = requestBodyJson["id"]
secureNetworkJson["master-key"] = requestBodyJson["key"]
secureNetworkFile.seek(0)
json.dump(secureNetworkJson, secureNetworkFile, indent=4)
secureNetworkFile.truncate()
secureNetworkFile.close()
self.send_response(204)
self.wfile.write("PUT success!\n".encode('utf8'))
self.end_headers()
return
客户端:
requestBody = {
"id": self.__secureNetwork.get_id(),
"key": self.__secureNetwork.get_key(),
"pairingMethod": ""
}
connection = http.client.HTTPConnection(address, pairingPort, timeout=60)
requestBodyJson = json.dumps(requestBody)
headers = {'Content-type': 'application/json'}
connection.request("PUT", pairingPath, body=requestBodyJson, headers=headers)
response = connection.getresponse()
当我在主线程上与服务器建立连接并使用上述代码发出 PUT 请求时,没有收到任何响应。self.send_response(204)
除非在 do_PUT() 的第一行,否则请求会挂起。我想根据情况打开并写入文件并发送响应代码,但这会导致客户端根本没有响应。我不确定在 do_PUT() 处理程序中还可以尝试什么来给客户端一个正确的响应。有什么我可以尝试的吗?