开发者

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)
    ht开发者_JAVA百科tpd = server_class(server_address, handler_class)
    while keep_running():
        httpd.handle_request()
        do_something_else()


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜