How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?

后端 未结 10 1193
渐次进展
渐次进展 2020-12-01 04:53

I am running my HTTPServer in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 05:49

    Another way to do it, based on http://docs.python.org/2/library/basehttpserver.html#more-examples, is: instead of serve_forever(), keep serving as long as a condition is met, with the server checking the condition before and after each request. For example:

    import CGIHTTPServer
    import BaseHTTPServer
    
    KEEP_RUNNING = True
    
    def keep_running():
        return KEEP_RUNNING
    
    class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
        cgi_directories = ["/cgi-bin"]
    
    httpd = BaseHTTPServer.HTTPServer(("", 8000), Handler)
    
    while keep_running():
        httpd.handle_request()
    

提交回复
热议问题