溫馨提示×

FastAPI中怎么實現懶加載

小億
109
2024-05-11 11:33:53
欄目: 編程語言

要在FastAPI中實現懶加載,可以使用Python的 functools 模塊中的 lru_cache 裝飾器。 lru_cache 裝飾器可以緩存函數的結果,并在下次調用相同參數時返回緩存的結果,從而實現懶加載。

以下是一個使用 lru_cache 裝飾器實現懶加載的示例代碼:

from fastapi import FastAPI
from functools import lru_cache

app = FastAPI()

@lru_cache
def expensive_operation():
    print("Performing expensive operation...")
    return "Result of expensive operation"

@app.get("/")
async def root():
    result = expensive_operation()
    return {"message": result}

在上面的示例中,expensive_operation 函數是一個耗時的操作,使用 lru_cache 裝飾器可以將其結果緩存起來,避免每次請求都執行這個耗時的操作。當第一次調用 expensive_operation 函數時,會執行耗時的操作,然后將結果緩存起來。當下次再次調用該函數時,將直接返回緩存的結果,而不需要再次執行耗時的操作。

通過這種方式,可以實現在FastAPI中的懶加載行為。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女