Python - stop WSGI application after specific request
Question: I need to create an application that ends after receiving a specific request.
I use `wsgiref.simple_server` and run handling request in separate thread.
There is my code:

    
    
    from wsgiref.simple_server import make_server
    import re
    import threading
    import urllib2
    
    def webapp(environ, start_response):
        path = environ.get('PATH_INFO', '').lstrip('/')
        for regex, callback in urls:
            match = re.search(regex, path)
            if match is not None:
                environ['app.url_args'] = match.groups()
                return callback(environ, start_response)
        return not_found(environ, start_response)
    
    KEEP_RUNNING = True
    srv = make_server('localhost', 8081, webapp)
    
    def t_serve():
        while KEEP_RUNNING:
            srv.handle_request()
    
    def main():
        t = threading.Thread(target=t_serve)
        t.start()
        print 'Service is running.'
        t.join()
    
    def index(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return ['Service works']
    
    def t_stop_service():
        print 'Service shutdown'
        urllib2.urlopen('http://localhost:8081/')
    
    def stop_service(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        global KEEP_RUNNING
        KEEP_RUNNING = False
        threading.Thread(target=t_stop_service).start()
        return ['Service is stopping']
    
    def not_found(environ, start_response):
        """Called if no URL matches."""
        start_response('404 NOT FOUND', [('Content-Type', 'text/html')])
        return ['<h1>Not Found</h1>']
    
    urls = [
        (r'^$', index),
        (r'^stop/?$', stop_service)
    ]
    
    if __name__ == '__main__':
        main()
    

After I make request "stop" request processing ends, but the process of the
program is not ending. How to fix it?


Answer: Depends on the WSGI server whether it will work, with good quality ones it
usually doesn't for good reasons, but have you tried using `sys.exit()` from
the request handler?

If you must, you could also use `os._exit(1)`. This will cause Python to exit
immediately, although it will not allow any cleanup code to run.

