Python 3 Simple HTTPS server [closed]

I know you can create a simple HTTP web server in Python 3 using

python -m http.server

However is there a simple way to secure the connection to the WebServer, do i need to generate certificates? How would I do this?


First, you will need a certificate - assume we have it in a file localhost.pem which contains both the private and public keys, then:

import http.server, ssl

server_address = ('localhost', 4443)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
                               server_side=True,
                               certfile='localhost.pem',
                               ssl_version=ssl.PROTOCOL_TLS)
httpd.serve_forever()

Make sure you specify the right parameters for wrap_socket!

Note: If you are using this to serve web traffic, you will need to use '0.0.0.0' in place of 'localhost' to bind to all interfaces, change the port to 443 (the standard port for HTTPS), and run with superuser privileges in order to have the permission to bind to a well-known port.