Python web server - performing other tasks

Using the following example, I can start the base web server, but my problem is that handle_request () blocks do_something_else () until a request arrives. Is there any way around this so that the web server runs the other backside of the task?

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()
+3
source share
2 answers

You can use multiple threads of execution through the Python streaming module . The following is an example:

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 trigger a thread that starts do_something_else()to run in front of your web server. When the server shuts down, the call join()terminates do_something_elsebefore the program exits.

+2
source

thread, HTTP- , do_something_else().

0

Source: https://habr.com/ru/post/1756798/


All Articles