Snippet/Python/HTTPServer+SSL+Thread

De Lea Linux
Aller à la navigation Aller à la recherche

Snippet d'un code sous Python avec HTTPServer, support TLS/SSL et Multithreading :

#!/usr/bin/python3

import ssl
import http.server
import socketserver


class ServerHandler(http.server.BaseHTTPRequestHandler):
        def do_GET(self):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write(bytes("Hello World", 'utf-8'))
                return


class ThreadedServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
        """Init a threaded server (handler)"""

if __name__ == '__main__':
        try:
                server = ThreadedServer(('localhost', 8443), ServerHandler)
                server.socket = ssl.wrap_socket(server.socket,
                                                server_side=True,
                                                do_handshake_on_connect=True,
                                                certfile="dummy.crt",
                                                keyfile="dummy.key")
                server.serve_forever()

        except KeyboardInterrupt:
                print("Shuttind down server")
                server.socket.close()