我正在使用Flask开发一个小型Web服务,需要运行后台任务,最好是通过任务队列。然而,在搜索该主题后,唯一的结果似乎就是Celery和Redis Queue,它们需要单独的排队服务,因此部署起来过于繁琐。由于我只想要一个简单的后台任务队列,可以在不同的线程/进程上排队和执行任务,是否有人知道是否有类似Python的工具可用?
我正在使用Flask开发一个小型Web服务,需要运行后台任务,最好是通过任务队列。然而,在搜索该主题后,唯一的结果似乎就是Celery和Redis Queue,它们需要单独的排队服务,因此部署起来过于繁琐。由于我只想要一个简单的后台任务队列,可以在不同的线程/进程上排队和执行任务,是否有人知道是否有类似Python的工具可用?
import threading
import time
class BackgroundTasks(threading.Thread):
def run(self,*args,**kwargs):
while True:
print('Hello')
time.sleep(1)
t = BackgroundTasks()
t.start()
Asyncio 库可能是你正在寻找的内容。
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
# Python 3.7+
asyncio.run(main())
如果您正在使用 FastAPI,则已经实现了BackgroundTasks。
在接收请求后执行后台任务时,不需要实现线程和队列。
代码实现:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
# function that will run in background after sending the response
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Tasks are happening in background"}
uwsgi
默认甚至不允许线程。这也使得代码更难测试和维护。在这种情况下,已经有一个被广泛接受的标准来实现这个目标:Celery
。 - jordanm