Friday, January 3, 2014

Bottle with SSL

Bottle with SSL

I was looking into using the bottle python web framework with SSL, and came across a few links on Google. They all seemed to use other third party modules for adding SSL support, and when I came across this post explaining how to add SSL to the built-in SimpleHTTPServer, I wondered if the same could be done with bottle.

It can. We just need to create a custom bottle.ServerAdapter which wraps the socket with ssl. The following should create a very basic SSL server using bottle (you need to create a ssl certificate first, I'm assuming it's called 'server.pem' in the following):

# Trying SSL with bottle
# ie combo of
# and
# without cherrypy?
# requires ssl

# to create a server certificate, run eg
# openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# DON'T distribute this combined private/public key to clients!
# (see
from bottle import Bottle, get, run, ServerAdapter

# copied from bottle. Only changes are to import ssl and wrap the socket
class SSLWSGIRefServer(ServerAdapter):
    def run(self, handler):
        from wsgiref.simple_server import make_server, WSGIRequestHandler
        import ssl
        if self.quiet:
            class QuietHandler(WSGIRequestHandler):
                def log_request(*args, **kw): pass
            self.options['handler_class'] = QuietHandler
        srv = make_server(, self.port, handler, **self.options)
        srv.socket = ssl.wrap_socket (
         certfile='server.pem',  # path to certificate

def get_x():
 return "Hi there"

#instead of:
#run(host="", port=8090)
#we use:
srv = SSLWSGIRefServer(host="", port=8090)

And that's it. You should now be able to go to https://localhost:8090/x and see 'Hi there'. The file's also available on github.