日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)FastAPI教程:FastAPI教程后臺任務

您可以定義在返回響應后運行的后臺任務。

這對于需要在請求之后發(fā)生的操作很有用,但客戶端實際上不必在接收響應之前等待操作完成。

這包括,例如:

  • 執(zhí)行操作后發(fā)送的電子郵件通知:由于連接到電子郵件服務器并發(fā)送電子郵件往往“緩慢”(幾秒鐘),因此您可以立即返回響應并在后臺發(fā)送電子郵件通知。
  • 處理數(shù)據(jù):例如,假設您收到一個必須經(jīng)過緩慢處理的文件,您可以返回“已接受”(HTTP 202)響應并在后臺處理它。

使用 BackgroundTasks

首先,BackgroundTasks在路徑操作函數(shù)中導入并定義一個參數(shù),類型聲明為BackgroundTasks:

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"}

FastAPI將為您創(chuàng)建類型對象BackgroundTasks并將其作為該參數(shù)傳遞。

創(chuàng)建任務函數(shù)

創(chuàng)建一個作為后臺任務運行的函數(shù)。

它只是一個可以接收參數(shù)的標準函數(shù)。

它可以是一個async def或正常的def函數(shù),F(xiàn)astAPI會知道如何正確處理它。

在這種情況下,任務函數(shù)將寫入文件(模擬發(fā)送電子郵件)。

由于寫操作不使用asyncand await,我們用 normal 定義函數(shù)def:

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"}

添加后臺任務

在您的路徑操作函數(shù)中,使用以下方法將您的任務函數(shù)傳遞給后臺任務對象.add_task():

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"}

.add_task() 作為參數(shù)接收:

  • 要在后臺運行的任務函數(shù) ( write_notification)。
  • 應該按順序傳遞給任務函數(shù)的任何參數(shù)序列 ( email)。
  • 應該傳遞給任務函數(shù)的任何關鍵字參數(shù) ( message="some notification")。

依賴注入

使用BackgroundTasks也適用于依賴注入系統(tǒng),您可以BackgroundTasks在多個級別聲明類型的參數(shù):在路徑操作函數(shù)中,在依賴項(可靠)中,在子依賴項中等。

FastAPI知道在每種情況下要做什么以及如何重用相同的對象,以便將所有后臺任務合并在一起,然后在后臺運行:

from typing import Optional

from fastapi import BackgroundTasks, Depends, FastAPI

app = FastAPI()


def write_log(message: str):
    with open("log.txt", mode="a") as log:
        log.write(message)


def get_query(background_tasks: BackgroundTasks, q: Optional[str] = None):
    if q:
        message = f"found query: {q}\n"
        background_tasks.add_task(write_log, message)
    return q


@app.post("/send-notification/{email}")
async def send_notification(
    email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
):
    message = f"message to {email}\n"
    background_tasks.add_task(write_log, message)
    return {"message": "Message sent"}

在此示例中,消息將在發(fā)送響應后寫入log.txt文件。

如果請求中有查詢,它將在后臺任務中寫入日志。

然后在路徑操作函數(shù)中生成的另一個后臺任務將使用email路徑參數(shù)寫入一條消息。

技術細節(jié)

該類BackgroundTasks直接來自starlette.background.

它直接導入/包含到 FastAPI 中,以便您可以從中導入它fastapi并避免意外導入替代項BackgroundTask(沒有s末尾) from starlette.background。

通過只使用BackgroundTasks(而不是BackgroundTask),就可以將其用作路徑操作函數(shù)參數(shù),并讓FastAPI為您處理其余部分,就像Request直接使用對象時一樣。

它仍然可以BackgroundTask在 FastAPI 中單獨使用,但您必須在代碼中創(chuàng)建對象并返回Response包含它的 Starlette 。

您可以在Starlette 的后臺任務官方文檔中查看更多詳細信息。

警告

如果您需要執(zhí)行繁重的后臺計算并且您不一定需要它由同一進程運行(例如,您不需要共享內(nèi)存、變量等),您可能會受益于使用其他更大的工具,如芹菜。

它們往往需要更復雜的配置、消息/作業(yè)隊列管理器,如 RabbitMQ 或 Redis,但它們允許您在多個進程中運行后臺任務,尤其是在多個服務器中。

要查看示例,請檢查Project Generators,它們都包含已配置的 Celery。

但是,如果您需要從同一個FastAPI應用程序訪問變量和對象,或者您需要執(zhí)行小型后臺任務(例如發(fā)送電子郵件通知),則只需使用BackgroundTasks.

回顧

BackgroundTasks在路徑操作函數(shù)和依賴項中導入并使用參數(shù)添加后臺任務。


本文名稱:創(chuàng)新互聯(lián)FastAPI教程:FastAPI教程后臺任務
當前路徑:http://www.dlmjj.cn/article/dhdgidd.html