16

I am trying to figure out how to run my overloaded customized BaseHTTPServer instance in the background after running the "".serve_forever() method.

Normally when you run the method execution will hang until you execute a keyboard interrupt, but I would like it to serve requests in the background while continuing script execution. Please help!

3 Answers 3

17

You can start the server in a different thread: https://docs.python.org/3/library/_thread.html#thread.start_new_thread

So something like:

import _thread as thread

def start_server():
    # Setup stuff here...
    server.serve_forever()
    
# start the server in a background thread
thread.start_new_thread(start_server, ())
    
print('The server is running but my script is still executing!')
Sign up to request clarification or add additional context in comments.

1 Comment

How do I stop the server thread once it is started?
2

I was trying to do some long-term animation using async and thought I'd have to rewrite server to use aiohttp (https://docs.aiohttp.org/en/v0.12.0/web.html), but Olivers technique of using seperate thread saved me all that pain. My code looks like this, where MyHTTPServer is simply my custom sublass of HTTPServer

import threading
import asyncio
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import io
import threading

async def tick_async(server):        
    while True:
        server.animate_something()
        await asyncio.sleep(1.0)

def start_server():
    httpd.serve_forever()
    
try:
    print('Server listening on port 8082...')

    httpd = MyHTTPServer(('', 8082), MyHttpHandler)
    asyncio.ensure_future(tick_async(httpd))
    loop = asyncio.get_event_loop()
    t = threading.Thread(target=start_server)
    t.start()
    loop.run_forever()

Comments

0

Another example using concurrent.futures :

import concurrent.futures
import http.server

def run_http_server():
    port = 8080
    server_address = ('', port)
    httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
    httpd.serve_forever()

def run_parallel_http_server():
    executor = concurrent.futures.ThreadPoolExecutor()
    executor.submit(run_http_server)
    executor.shutdown(wait=False)

if __name__ == '__main__':
    run_parallel_http_server()
    # do something else..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.