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)
为什么我的程序中有两个不同的Queue对象,我希望它们只是一个。
或者有任何简单的方法可以做到这一点:;通过http请求添加任务并以正常函数"处理队列中的任务;
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