1) While the KeyboardInterrupt works, if I make more than 0 curls to
the server and then quit, I can't run it again right away and get
this:
socket.error: [Errno 48] Address already in use
Not all of my connections are closing properly. How do I fix this?
2) curling localhost:8080/quit does show the "Quitting" output that I
expect, but doesn't quit the server until I manually control-c it.
I think that I need *all* threads to close and not just the current
one, so I'm not quite sure how to proceed. Pointers in the right
direction are appreciated. And if there's a "better" way to do this
threading httpd server (subjective, I realize), please let me know!
Thanks.
Pete
#############################################
#!/usr/bin/env python
import SocketServer
import SimpleHTTPServer
PORT = 8080
done = False
class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
global done
if self.path=='/quit':
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write('Quitting')
done = True
return self
else:
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write('Unknown')
return self
if __name__ == "__main__":
httpd = SocketServer.ThreadingTCPServer(('localhost',
PORT),CustomHandler)
try:
while not done:
print "done: ", done
httpd.handle_request()
except KeyboardInterrupt:
print "Server is done."
httpd.server_close()
> I'm trying to get threading going for the first time in python, and
> I'm trying to modify code I found so that I can have the server close
> the TCP connections and exit gracefully. Two problems:
Which Python version?
> 1) While the KeyboardInterrupt works, if I make more than 0 curls to
> the server and then quit, I can't run it again right away and get
> this:
> socket.error: [Errno 48] Address already in use
>
> Not all of my connections are closing properly. How do I fix this?
>
> 2) curling localhost:8080/quit does show the "Quitting" output that I
> expect, but doesn't quit the server until I manually control-c it.
On Python 2.6, you should call the shutdown() method (from another
thread!) instead of simply server_close()
See this recipe [1] -- just look at the main() function (disregard all the
previous details); it runs the server(s) in their own thread, the main
thread just sits and waits for KeyboardInterrupt or SystemExit.
[1] http://code.activestate.com/recipes/577025
--
Gabriel Genellina