Search code examples
linuxwsgicherrypywsgiserver

How to stop WsgiServer in Linux


I am a newbee in cherrypy. I just tried with a sample program of wsgiserver.The program is as follows

from cherrypy import wsgiserver

def my_crazy_app(environ, start_response):
  status = '200 OK'
  response_headers = [('Content-type','text/plain')]
  start_response(status, response_headers)
  return ['Hello world!']

server = wsgiserver.CherryPyWSGIServer(
        ('127.0.0.1', 8080), my_crazy_app,
        server_name='localhost')
server.start()

I got the output Hello world successfully, but the problem is when i hit Ctrl-c on the terminal to stop the server, its not getting stopped. How to do it?


Solution

  • IIRC, the wsgiserver itself is not associated to any signal and therefore doesn't respect the SIGINT interruption. Only the higher level CherryPy engine will provide that. If you can't use it, you probably want to install a handler using the Python signal module.

    Well, something along those lines will do the job:

    import signal
    
    from cherrypy import wsgiserver 
    def my_crazy_app(environ, start_response): 
       status = '200 OK' 
       response_headers = [('Content-type','text/plain')] 
       start_response(status, response_headers) 
       return ['Hello world!'] 
    
    server = wsgiserver.CherryPyWSGIServer( ('127.0.0.1', 8080), my_crazy_app, server_name='localhost')
    
    def stop_server(*args, **kwargs):
      server.stop()
    
    signal.signal(signal.SIGINT,  stop_server)
    
    server.start()