3 from http.server import HTTPServer
5 def set_response_200_ok(self, payload = None):
6 self.send_response(200)
7 self.send_header('Content-Type', 'application/json')
10 self.wfile.write(payload)
12 def set_response_404_not_found(self):
13 self.send_response(404)
16 def set_response_500_server_error(self):
17 self.send_response(500)
20 def get_payload(self):
21 if self.headers['Content-Length'] == None:
22 raise Exception('Invalid payload, Content-Length not defined')
24 content_length = int(self.headers['Content-Length'])
25 return self.rfile.read(content_length)
27 def start_http_endpoint(port, handler_class):
28 _thread.start_new_thread(init_http_endpoints, (port, handler_class))
30 def start_https_endpoint(port, handler_class, keyfile, certfile, ca_certs):
31 _thread.start_new_thread(init_https_endpoints, (port, handler_class, keyfile, certfile, ca_certs))
33 def init_http_endpoints(port, handler_class, server_class=HTTPServer):
34 server = server_class(('', port), handler_class)
35 sa = server.socket.getsockname()
36 print("Serving HTTP on", sa[0], "port", sa[1], "for", handler_class, "...")
37 server.serve_forever()
39 def init_https_endpoints(port, handler_class, keyfile, certfile, ca_certs, server_class=HTTPServer):
40 server = server_class(('', port), handler_class)
41 server.socket = ssl.wrap_socket(server.socket, keyfile=keyfile, certfile=certfile,
42 ca_certs=ca_certs, server_side=True)
43 sa = server.socket.getsockname()
44 print("Serving HTTPS on", sa[0], "port", sa[1], "for", handler_class, "...")
45 server.serve_forever()