我有以下代碼:
from fastapi import FastAPI, Request, Form
import uvicorn
from testphoto.utils.logger import get_log
import datetime
import time
import asyncio
log = get_log()
app = FastAPI()
def process():
log.info("Sleeping at " str(datetime.datetime.now()))
time.sleep(5)
log.info("Woke up at " str(datetime.datetime.now()))
return "Sucess"
@app.post("/api/photos")
async def root(request: Request, photo: str = Form()):
process()
return {"message": "Hello World"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8008)
我想要做的是運行函式process并回傳回應,同時保持函式process運行。我已經閱讀了一些關于 asyncio 和 FastAPI 的檔案,但我仍然無法弄清楚這一點。為了使代碼完全按照我的意愿執行,您會指出我在哪里?
uj5u.com熱心網友回復:
您正在尋找的內容(如果不是 CPU 密集型的)稱為后臺任務。
您可以在檔案中閱讀更多內容:
https://fastapi.tiangolo.com/tutorial/background-tasks/
參考指南中有關如何使用后臺任務的示例:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
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": "Notification sent in the background"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/517032.html
