Python 3 Simple HTTPS server

PythonHttps

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMANICX100View Question on Stackoverflow
Solution 1 - PythonMichael FoukarakisView Answer on Stackoverflow