The Twisted web howto doesn't mention the fairly common task of creating an SSL-secured communications channel for a web server. The process of doing so is fairly simple, but it requires tracking down a few pieces of information, so I've collected them here:
First things first, to create an SSL server, you need a private key file, and an SSL server certificate. Let's assume for the moment that you're a software developer who just wants to get a testing system set up, so you're not going to go to the trouble of getting a formal public certificate, you just want something for testing. OpenSSL can help here. First, we generate a private key file:
openssl genrsa > privkey.pemThen we generate a self-signed SSL certificate:
openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1000Okay, that's the first challenge licked. Next thing is to actually create the server. We assume that you've created a site as in the Twisted web howto, so you should now have a site object, and you know the port on which you want to listen. We import the ssl module, create an SSL context for the server, and then call listenSSL on the reactor with our port, site and context:
from twisted.internet import reactor, ssl
sslContext = ssl.DefaultOpenSSLContextFactory(
port, # integer port
site, # our site object, see the web howto
contextFactory = sslContext,
There are also facilities in twisted.application for setting up the port given the context and site, but I'm going for the simple to-the-metal approach here to match up with the original howto's introductory example.
Pingbacks are closed.