I'm running many web servers on the same machine for test purposes. Instead of dealing with server port conflicts, I'd like to have the servers simply ask the OS for an available port, and then tell me what they got.
I may communicate the port back to the invoker by logging to console, or writing to a specified temp file (not sure yet), but knowing the port number is the tricky part.
Currently, the WSGI based server is being launched with:
cherrypy.quickstart(dev_server, config=_GetConfig(options))
The config will contain the following:
{ 'global':
{ <snip>
'server.socket_host': '0.0.0.0',
'server.socket_port': int(options.port)
},
<snip>
}
Is there any way to do this with CherryPy?
I assume I can set the port to '0' to have it auto-selected, but that doesn't give me a way to report it.
The basic idea is:
The first part depends radically on how you're building, starting, and configuring your servers. CherryPy is hugely flexible, and the details will be different depending on how you're using it.
The second part requires that you be using some mechanism where you're writing the top-level code that starts the servers, and not one of the mechanisms that starts them automatically without any of your code. That's because, before starting the server, you will need to manually bind
the server to get its socket. Once you have a created and bound socket, getsockname
will give you the address and port it ended up bound to.
The third part can obviously be as easy or as hard as you want.
Here's a trivial example, which you can even do from the interactive interpreter:
def app(env, start):
start('200 OK', [('Content-type', 'text/plain')])
return ['Hello, world!']
server = cherrypy.wsgiserver.CherryPyWSGIServer(('0.0.0.0', 0), app,
server_name='localhost')
server.bind(socket.AF_INET, socket.SOCK_STREAM)
addr, port = server.socket.getsockname()
print(port)
server.start()
You may also want to take a look at cherrypy.process.servers
and its ServerAdapter
, which lets you manage multiple servers from a single place, instead of having a bunch of independent servers that you have to manually coordinate.