'FastAPI can't access global queue?

I'm creating a local app. I'd like to be able to shutdown the server from am api call, but do not have any success.

Here're some code:

# q.py
from multiprocessing import Queue
q = Queue()
def stop_server(*args, **kwargs):
    q.put("EXTERMINATE")

# app.py
app = FastAPI()
@app.get("/kill")
def index(background_tasks: BackgroundTasks):
    background_tasks.add_task(stop_server)
    return {"killed": True}

# main.py
from q import q

def start_server():
    uvicorn.run(app="app:app", host="127.0.0.1", port=8080)
if __name__ == "__main__":
    server = Process(target=start_server)
    server.start()

    # sleep(5)
    # q.put("EXTERMINATE")
    # sleep(3)
    while True:
        msg = q.get()
        if msg == "EXTERMINATE":
            while server.is_alive():
                server.terminate()
                sleep(0.1)
            server.join(timeout=1)
            q.close()
            break

Accessing "127.0.0.1:8080/kill" does nothing.

There is a commented block that manually put a message into the queue. If you uncomment the code, you should see the server terminated successfully.

So, how could I access the queue from inside a fastapi handler?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source