tags:

views:

52

answers:

2

Hi guys. Using the following example I can get a basic web server running but my problem is that the handle_request() blocks the do_something_else() until a request comes in. Is there any way around this to have the web server do other back ground tasks?

def run_while_true(server_class=BaseHTTPServer.HTTPServer,
               handler_class=BaseHTTPServer.BaseHTTPRequestHandler):

    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    while keep_running():
        httpd.handle_request()
        do_something_else()
A: 

You should have a thread that handles http requests, and a thread that does do_something_else().

orangeoctopus
+2  A: 

You can use multiple threads of execution through the Python threading module. An example is below:

import threading

# ... your code here...

def run_while_true(server_class=BaseHTTPServer.HTTPServer,
               handler_class=BaseHTTPServer.BaseHTTPRequestHandler):

    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    while keep_running():
        httpd.handle_request()

if __name__ == '__main__':
    background_thread = threading.Thread(target=do_something_else)
    background_thread.start()
    # ... web server start code here...
    background_thread.join()

This will cause a thread which executes do_something_else() to start before your web server. When the server shuts down, the join() call ensures do_something_else finishes before the program exits.

Michael Mior
Perfect. Thanks!
William T Wild