CherryPy Project Download

Multiple HTTP Servers

Implementing multiple HTTP servers as described in CherryPy Essentials is no longer supported (see ticket #752, not there anymore?). I have been able to develop an alternative method that replaces it.

This method uses a configuration file, so you will have to rework it if you want the configuration data to be hard-coded.

Here is an example of the httpservers.ini configuration file:

#httpservers.ini
[HTTP_Addresses]
Host_1:192.168.0.10
Port_1:8080
Host_2:LOCALHOST# This will be changed to 127.0.0.1
Port_2:8008
Host_3:[::1]# IPv6 may not be valid on old systems
Port_3:# If blank or nonexistent will default to 80

Note that this is a standard format ini file, not the CherryPy version that requires values that are Python datatypes.

This file goes in the same folder as the sample page below.

Here is the source code for a sample page:

import os.path
import cherrypy
from cherrypy import _cpserver
from cherrypy import _cpwsgi_server
from ConfigParser import ConfigParser

class Home:

    def index(self):
        return 'Hello world from multiple addresses'

    index.exposed=True

pRoot=os.path.dirname(os.path.abspath(__file__))
fIni=ConfigParser()
fIni.readfp(open(os.path.join(pRoot,'httpservers.ini'),'rb'))
i=0;bFirst=True;lXSvrs=[];sSect='HTTP_Addresses'
while True:
    i+=1
    sOptHost='Host_%i'%i
    sOptPort='Port_%i'%i
    if fIni.has_option(sSect,sOptHost):
        sHost=fIni.get(sSect,sOptHost)
        if len(sHost)>0:
            if sHost.lower()=='localhost':
                sHost='127.0.0.1'
            try:
                iPort=fIni.getint(sSect,sOptPort)
            except:
                iPort=80
            if bFirst:
                bFirst=False
                cherrypy.config.update({
                    #'environment':'production',
                    'server.socket_host':sHost,
                    'server.socket_port':iPort,
                    'log.access_file':'access.log',
                    'log.error_file':'error.log',
                    'log.screen':True
                })
            else:
                lXSvrs.append(_cpwsgi_server.CPWSGIServer())
                lXSvrs[-1].bind_addr=(sHost,iPort)
                lXSvrs.append(_cpserver.ServerAdapter(cherrypy.engine,lXSvrs[-1],(sHost,iPort)))
                lXSvrs[-1].subscribe()
    else:
        break

cherrypy.tree.mount(Home(),'/',config={
    '/':{
        'tools.response_headers.on':True,
        'tools.response_headers.headers':[
            ('Content-Type','text/plain')
        ]
    }
})
cherrypy.engine.start()
cherrypy.engine.block()

Hosted by WebFaction

Log in as guest/cherrypy to create/edit wiki pages