you can use this command to generate a self-signed certificate

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

the openssl framework will ask you to enter some information, such as your country, city, etc. just follow the instruction, and you will get a cert.pem file. the output file will have both your RSA private key, with which you can generate your public key, and the certificate. the output file looks like this:

-----BEGIN RSA PRIVATE KEY-----
 # your private key
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
 # your certificate
-----END CERTIFICATE-----

just load it, and the ssl module will handle the rest for you:

context.load_cert_chain(certfile="cert.pem", keyfile="cert.pem")

btw, there is no "SSLContext" in python2. for guys who are using python2, just assign the pem file when wrapping socket:

newsocket, fromaddr = bindsocket.accept()
connstream = ssl.wrap_socket(newsocket,
                             server_side=True,
                             certfile="cert.pem",
                             keyfile="cert.pem",
                             ssl_version=YOUR CHOICE) 

available ssl version: ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23. if you have no idea, ssl.PROTOCOL_SSLv23 may be your choice as it provides the most compatibility with other versions.

Answer from Brian on Stack Overflow
🌐
Python
docs.python.org › 3 › library › ssl.html
ssl — TLS/SSL wrapper for socket objects — Python 3.14.4 ...
Passing SERVER_AUTH as purpose sets verify_mode to CERT_REQUIRED and either loads CA certificates (when at least one of cafile, capath or cadata is given) or uses SSLContext.load_default_certs() to load default CA certificates.
Discussions

How Do I Convert My Flask Server into HTTPS?

The idea to put Apache in front of your application and have Apache handle the HTTPS is a good one. I would personally reach for NGINX over Apache, but it's the same difference.

Here are some resources concerning this:

  • https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04

  • https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04

More on reddit.com
🌐 r/flask
22
16
November 12, 2018
Waitress — Production-quality pure-Python WSGI server with very acceptable performance and no dependencies.

Why? (quote from the docs):

At the time of the release of Waitress, there are already many pure-Python WSGI servers. Why would we need another?

Waitress is meant to be useful to web framework authors who require broad platform support. It’s neither the fastest nor the fanciest WSGI server available but using it helps eliminate the N-by-M documentation burden (e.g. production vs. deployment, Windows vs. Unix, Python 3 vs. Python 2, PyPy vs. CPython) and resulting user confusion imposed by spotty platform support of the current (2012-ish) crop of WSGI servers. For example, gunicorn is great, but doesn’t run on Windows. paste.httpserver is perfectly serviceable, but doesn’t run under Python 3 and has no dedicated tests suite that would allow someone who did a Python 3 port to know it worked after a port was completed. wsgiref works fine under most any Python, but it’s a little slow and it’s not recommended for production use as it’s single-threaded and has not been audited for security issues.

At the time of this writing, some existing WSGI servers already claim wide platform support and have serviceable test suites. The CherryPy WSGI server, for example, targets Python 2 and Python 3 and it can run on UNIX or Windows. However, it is not distributed separately from its eponymous web framework, and requiring a non-CherryPy web framework to depend on the CherryPy web framework distribution simply for its server component is awkward. The test suite of the CherryPy server also depends on the CherryPy web framework, so even if we forked its server component into a separate distribution, we would have still needed to backfill for all of its tests. The CherryPy team has started work on Cheroot, which should solve this problem, however.

Waitress is a fork of the WSGI-related components which existed in zope.server. zope.server had passable framework-independent test coverage out of the box, and a good bit more coverage was added during the fork. zope.server has existed in one form or another since about 2001, and has seen production usage since then, so Waitress is not exactly “another” server, it’s more a repackaging of an old one that was already known to work fairly well.

More on reddit.com
🌐 r/Python
53
46
March 13, 2012
[AF] Creating a HTTPS web server with Flask_script Manager.

OK, looks like I got it figured out:

In my manage.py file:

from OpenSSL  import SSL
context = ('app/host-2.cert', 'app/host-2.key')
:
manager.add_command('runserver', Server('localhost', port=5000, **ssl_**context=context))

I did try this last night but using context instead of ssl_context: manager.add_command('runserver', Server('localhost', port=5000, context=context))

So that explains why it was failing for me. Anyway, I've answered the question, hopefully this thread will help someone in the future.

More on reddit.com
🌐 r/flask
1
10
March 13, 2017
HTTPS server with Python

This appears to be related to how the requests module validates certificates rather than anything to do with Python/your server. See:

http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification

You may want to double-check your use of the cert keyword arg. Specifically, make sure the path is correct and make sure that, if your cert file doesn't include the key, you are passing a tuple with paths to both the cert and key.

Unfortunately, I can't speak to #2.

More on reddit.com
🌐 r/learnpython
2
4
December 9, 2013
🌐
GitHub
gist.github.com › oborichkin › d8d0c7823fd6db3abeb25f69352a5299
Simple TLS client and server on python · GitHub
import socket import ssl HOST = "127.0.0.1" PORT = 40000 if __name__ == "__main__": server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server = ssl.wrap_socket( server, server_side=True, keyfile="path/to/keyfile", certfile="path/to/certfile" ) server.bind((HOST, PORT)) server.listen(0) while True: connection, client_address = server.accept() while True: data = connection.recv(1024) if not data: break print(f"Received: {data.decode('utf-8')}") ... To avoid getting the deprecation warning and update the code SSLContext method must be used and the unwrapped socket closed as specified at https://pythontic.com/ssl/sslcontext/sslcontext :
🌐
Paullockaby
paullockaby.com › posts › 2019 › 03 › python-ssl-socket-server
Python SSL Socket Server - Paul Lockaby
I’m pretty certain that this code is valid in Python 3.7, though we are running it in a 3.6 environment. First, the server. import socketserver import ssl class RequestServer(socketserver.ThreadingMixIn, socketserver.TCPServer): # faster re-binding allow_reuse_address = True # kick connections when we exit daemon_threads = True def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): super().__init__(server_address, RequestHandlerClass, False) # create an ssl context that using the dart.s.uw.edu cert that requires # the client to present a certificate and validates it against uwca.
🌐
Electricmonk
electricmonk.nl › log › 2018 › 06 › 02 › ssl-tls-client-certificate-verification-with-python-v3-4-sslcontext
SSL/TLS client certificate verification with Python v3.4+ SSLContext | Electricmonk.nl weblog
June 2, 2018 - Normally you’d use a server certificate from a Certificate Authority such as Let’s Encrypt, and would setup your own Certificate Authority so you can sign and revoke client certificates. ... Make sure to enter ‘example.com’ for the Common Name. ... The Common Name for the client certificate doesn’t really matter. ... #!/usr/bin/python3 import socket import ssl host_addr = '127.0.0.1' host_port = 8082 server_sni_hostname = 'example.com' server_cert = 'server.crt' client_cert = 'client.crt' client_key = 'client.key' context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=server_cert) context.load_cert_chain(certfile=client_cert, keyfile=client_key) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn = context.wrap_socket(s, server_side=False, server_hostname=server_sni_hostname) conn.connect((host_addr, host_port)) print("SSL established.
🌐
Pythontic
pythontic.com › ssl › sslsocket › introduction
The SSLSocket class in Python | Pythontic.com
The SSL server program creates a server socket and listens on port 15001 on localhost.
🌐
Snyk
snyk.io › blog › implementing-tls-ssl-python
Implementing TLS/SSL in Python | Snyk
October 16, 2022 - Next, we wrapped the socket with SSL by specifying the path to our certificate in the wrap_socket method. Finally, we ran the server at the bottom of the file. To connect a client, you can use the Python requests module to make a GET request to the server address:
Find elsewhere
🌐
Python
docs.python.org › 3.0 › library › ssl.html
ssl — SSL wrapper for socket objects — Python v3.0.1 documentation
Takes an instance sock of socket.socket, and returns an instance of ssl.SSLSocket, a subtype of socket.socket, which wraps the underlying socket in an SSL context. For client-side sockets, the context construction is lazy; if the underlying socket isn’t connected yet, the context construction will be performed after connect() is called on the socket. For server-side sockets, if the socket has no remote peer, it is assumed to be a listening socket, and the server-side SSL wrapping is automatically performed on client connections accepted via the accept() method.
🌐
GitHub
github.com › xliu59 › SSL-TLS_SOCKET
GitHub - xliu59/SSL-TLS_SOCKET: A basic implementation on SSL/TLS socket on both server and client
python server.py --sslv23 --cacert ./ssl/certificate.pem --cipher ECDHE-RSA-AES256-GCM-SHA384 127.0.0.1 8801 index.html
Starred by 13 users
Forked by 4 users
Languages   Python 99.1% | HTML 0.9% | Python 99.1% | HTML 0.9%
🌐
Markusholtermann
markusholtermann.eu › 2016 › 09 › ssl-all-the-things-in-python
Markus Holtermann — SSL All The Things In Python
And finally you connect to the server. import socket, ssl HOST, PORT = 'example.com', 443 def handle(conn): conn.write(b'GET / HTTP/1.1\n') print(conn.recv().decode()) def main(): sock = socket.socket(socket.AF_INET) context = ssl.create_de...
🌐
Medium
nishanc.medium.com › how-to-development-server-with-ssl-enabled-using-python3-a1065c1629dc
How to: Development Server with SSL Enabled using Python3 | by Nishān Wickramarathna | Medium
September 27, 2019 - On Linux, usually default python version is 2.x so you might need to install python 3.x, hence python3 server.py · Then navigate to https://localhost:4443 · That’s it. Please comment if any on the links do not work or if you have questions.
🌐
Martin Pitt
piware.de › 2011 › 01 › creating-an-https-server-in-python
Creating an HTTPS server in Python · Martin Pitt
January 4, 2011 - After reading some docs and playing ... context.load_cert_chain(certfile='/tmp/cert.pem', keyfile='/tmp/key.pem') context.check_hostname = False with HTTPServer(("localhost", 4443), SimpleHTTPRequestHandler) as httpd: httpd.socket = context.wrap_socket(httpd.socket, server_side=True) ...
🌐
Plain English
plainenglish.io › blog › python-simple-http-server-with-ssl-certificate-encrypted-traffic-73ffd491a876
Python Simple HTTP Server With SSL Certificate (Encrypted Traffic)
August 19, 2022 - In this example, I use step 2 for generating an SSL certificate. So, now I just have cert.pem. If you have a private key and cert file. Just read this information below for a little enhancement in your code. Information from https://docs.python.org/3/library/ssl.html#ssl-contexts · The next step is to create a file called https-simple-server.py or anything you want to be the name of the file.
🌐
Jython
jython.org › jython-old-sites › docs › library › ssl.html
17.3. ssl — SSL wrapper for socket objects — Jython v2.5.2 documentation
To test for the presence of SSL support in a Python installation, user code should use the following idiom: try: import ssl except ImportError: pass else: [ do something that requires SSL support ] This example connects to an SSL server, prints the server’s address and certificate, sends ...
🌐
Anvileight
anvileight.com › blog › posts › simple-python-http-server
Python HTTP(S) Server — Example
In both cases contents of the current folder will be accessible via http://127.0.0.1:8000 · To run secure HTTPs server create a following module: from http.server import HTTPServer, BaseHTTPRequestHandler import ssl httpd = HTTPServer(('localhost', 4443), BaseHTTPRequestHandler) httpd.socket ...
🌐
GitHub
gist.github.com › dergachev › 7028596
simple-https-server.py · GitHub
Updated to Python 3.11.4 (http.server module changes, ssl module changes/deprecations) from http.server import HTTPServer, SimpleHTTPRequestHandler import ssl from pathlib import Path port = 4443 httpd = HTTPServer(("localhost", port), SimpleHTTPRequestHandler) ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ssl_context.load_cert_chain(Path(__file__).parent / "server.pem") httpd.socket = ssl_context.wrap_socket( httpd.socket, server_side=True, ) print(f"Serving on https://localhost:{port}") httpd.serve_forever() Copy link ·
🌐
Linux Hint
linuxhint.com › python-ssl-example
Python SSL Example
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
A Security Site
asecuritysite.com › subjects › chapter107
Client/server with SSL
Bib: @misc{asecuritysite_19014, title = {Client/server with SSL}, year={2026}, organization = {Asecuritysite.com}, author = {Buchanan, William J}, url = {https://asecuritysite.com/subjects/chapter107}, note={Accessed: April 12, 2026}, howpublished={\url{https://asecuritysite.com/subjects/chapter107}} }