Skip to content

Instantly share code, notes, and snippets.

@gh640
Created March 7, 2021 01:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gh640/3c54c2eb5a8af889e3ab5f49cc4befc6 to your computer and use it in GitHub Desktop.
Save gh640/3c54c2eb5a8af889e3ab5f49cc4befc6 to your computer and use it in GitHub Desktop.
Sample: A simple https server with Python for development (Python 3.9+).
"""Simple https server for development."""
import ssl
from http.server import HTTPServer, SimpleHTTPRequestHandler
CERTFILE = './localhost.pem'
def main():
https_server(certfile=CERTFILE)
def https_server(*, certfile):
print('`https_server()` starts...')
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(CERTFILE)
server_address = ('', 443)
with HTTPServer(server_address, SimpleHTTPRequestHandler) as httpd:
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
print_server_info(httpd)
try:
httpd.serve_forever()
except Exception as e:
httpd.server_close()
raise e
def print_server_info(server):
print(f"""Server info:
name: {server.server_name}
address: {server.server_address}
""")
if __name__ == "__main__":
main()
@gh640
Copy link
Author

gh640 commented Mar 7, 2021

The self-signed cert file localhost.pem needs to be prepared beforehand.

openssl req -new -x509 -keyout localhost.pem -out localhost.pem -days 365 -nodes

Output sample:

$ python simple-https-server.py
`https_server()` starts...
Server info:
    name: Hayatos-MacBook-Pro.local
    address: ('0.0.0.0', 443)

@gh640
Copy link
Author

gh640 commented Mar 7, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment