Last active
October 31, 2015 15:12
-
-
Save allanlei/2cdc247ee25e2cbd2887 to your computer and use it in GitHub Desktop.
Twisted HTTP server example with vhosts and HTTPS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Usage: twistd -ny vhost.py | |
""" | |
from __future__ import absolute_import, division, unicode_literals, print_function | |
import os | |
from twisted.application import internet, service | |
from twisted.internet import reactor, ssl | |
from twisted.web import vhost, server | |
from twisted.web.static import File | |
from twisted.web.wsgi import WSGIResource | |
from flask import Flask, current_app, request | |
PRIVATE_KEY = b""" | |
-----BEGIN PRIVATE KEY----- | |
... | |
-----END PRIVATE KEY----- | |
""" | |
PUBLIC_KEY = b""" | |
-----BEGIN CERTIFICATE----- | |
... | |
-----END CERTIFICATE----- | |
""" | |
CA_BUNDLE_PEM = b""" | |
-----BEGIN CERTIFICATE----- | |
... | |
-----END CERTIFICATE----- | |
-----BEGIN CERTIFICATE----- | |
... | |
-----END CERTIFICATE----- | |
-----BEGIN CERTIFICATE----- | |
... | |
-----END CERTIFICATE----- | |
""" | |
certificate = ssl.PrivateCertificate.loadPEM(os.linesep.join([PRIVATE_KEY, PUBLIC_KEY])) | |
ca_bundle = ssl.Certificate.loadPEM(CA_BUNDLE_PEM) | |
default, flask1, flask2 = Flask('default'), Flask('flask1'), Flask('flask2') | |
@default.route('/') | |
@flask1.route('/') | |
@flask2.route('/') | |
def index(): | |
return 'I am {} responding to {}'.format(current_app.name, request.url) | |
vhosts = vhost.NameVirtualHost() | |
vhosts.default = WSGIResource(reactor, reactor.getThreadPool(), default) | |
vhosts.addHost('example.com', File(b'/tmp')) | |
vhosts.addHost('exmaple.org', WSGIResource(reactor, reactor.getThreadPool(), flask1)) | |
vhosts.addHost('example.net', WSGIResource(reactor, reactor.getThreadPool(), flask2)) | |
application = service.Application('vhost Testing') | |
http = internet.TCPServer(8000, server.Site(vhosts)) | |
http.setServiceParent(application) | |
https = internet.SSLServer(4443, server.Site(vhosts), ssl.CertificateOptions( | |
privateKey=certificate.privateKey.original, | |
certificate=certificate.original, | |
extraCertChain=[ | |
ca_bundle.original, | |
], | |
)) | |
https.setServiceParent(application) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment