Home
> Uncategorized > Creating a server that serves both over HTTP and HTTPS
Creating a server that serves both over HTTP and HTTPS
First let’s look at the code:
""" Python 27 CherryPy 3.2.2 """ import cherrypy DEBUG = False class ServerMain(object): ''' A class that represents and encapsulates methods for communicating with the server ''' def index(self): ''' Method that handles the index page If the debug mode is on, then display a page for uploading files ''' if(DEBUG): return """</pre> <h2>Upload a file</h2> <form action="upload" enctype="multipart/form-data" method="post"> filename: <input type="file" name="myFile" /> <input type="submit" /> </form> <h2>Download a file</h2> <pre> <a href="download">This one</a> """ else: return """ </pre> <h2>Status: OK</h2> <pre> """ index.exposed = True def upload(self, myFile): ''' Method that handles uploads. A file handle will be attached to the parameter when an upload is done. Note that the name of "myFile" argument is important since the client code needs to use that as the file name key parameter when uploading data. ''' out = open("uploaded/"+myFile.filename, 'wb') while True: data = myFile.file.read(8192) if not data: break out.write(data) out.close() return "OK" uploadx.exposed = True if __name__ == '__main__': ''' Main. Initialize server instances. ''' cherrypy.tree.mount(ServerMain()) cherrypy.server.unsubscribe() HTTPS_SERVER = cherrypy._cpserver.Server() HTTPS_SERVER.socket_port = 8443 HTTPS_SERVER._socket_host = '0.0.0.0' HTTPS_SERVER.max_request_body_size = 120 * 1024 # ~100kb HTTPS_SERVER.thread_pool = 30 HTTPS_SERVER.ssl_module = 'pyopenssl' HTTPS_SERVER.ssl_certificate = 'server.crt' HTTPS_SERVER.ssl_private_key = 'server.key' #HTTPS_SERVER.ssl_certificate_chain = '/home/ubuntu/gd_bundle.crt' HTTPS_SERVER.subscribe() HTTP_SERVER = cherrypy._cpserver.Server() HTTP_SERVER.socket_port = 8080 HTTP_SERVER._socket_host = "0.0.0.0" HTTP_SERVER.max_request_body_size = 120 * 1024 # ~100kb HTTP_SERVER.thread_pool = 30 HTTP_SERVER.subscribe() cherrypy.engine.start() cherrypy.engine.block()
This is how you create such a server which is definitely as simple as it looks. Basically, you create two server instance and dedicate one to HTTP while you dedicate the other for HTTPS. Nevertheless, the SSL functionality of CherryPy has some bugs which can make your server crash. Occasionally you may get an assertion error like AssertionError: recv(8192) returned 16384 bytes. See this link for a fix for that case. You may also get an error like AttributeError: ‘module’ object has no attribute ‘socket_errors_to_ignore’. For that error, see this link.
References: http://www.zacwitte.com/running-cherrypy-on-multiple-ports-example
Categories: Uncategorized
Comments (0)
Trackbacks (1)
Leave a comment
Trackback
-
December 11, 2012 at 7:57 pmSetting up an HTTPS (SSL) Server using CherryPy | Brownian Hacking