Search code examples
pythonfastapiuvicorn

how to share a global Queue between a normal function and a route request function in python fastapi


import queue
import threading
import time
import uvicorn
from fastapi import FastAPI
task_queue = queue.Queue()
app = FastAPI()
@app.get("/")
def hello_world():
    task_queue.put('task')
    print(task_queue, task_queue.qsize())
    return {"Hello": "World"}
def handle_tasks():
    while True:
        print(task_queue, task_queue.qsize())
        time.sleep(5)
if __name__ == "__main__":
    threading.Thread(target=handle_tasks, args=()).start()
    uvicorn.run("test:app", host="0.0.0.0", port=8000, workers=1)

Why there are two different Queue object in my program, I want them to be only one.

Or there are any simple way to do this: "add a task by a http request and handle the tasks in a queue in a normal function"


Solution

  • import logging
    import time
    from fastapi import FastAPI
    from fastapi_utils.tasks import repeat_every
    
    logger = logging.getLogger(__name__)
    app = FastAPI()
    counter = 0
    
    @app.get('/')
    def hello():
        return 'Hello'
    
    @app.on_event("startup")
    @repeat_every(seconds=1, logger=logger, wait_first=True)
    def periodic():
        global counter
        print('counter is', counter)
        counter += 1
    

    https://github.com/tiangolo/fastapi/issues/520#issuecomment-667428023