William T Wild
William T Wild

Reputation: 1032

Python Web Server - Getting it to do other tasks

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()

Upvotes: 3

Views: 1034

Answers (2)

Michael Mior
Michael Mior

Reputation: 28762

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.

Upvotes: 2

Donald Miner
Donald Miner

Reputation: 39943

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

Upvotes: 0

Related Questions