[英]Any way to process SQS messages asynchronously through FastAPI without BackgroundTasks?
我一直在尋找使用 FastAPI 實現后台作業的方法。 我有一個 API /api/event
來驗證傳入的請求,並將要處理的事件添加到 SQS 隊列,如果事件被接受,則將 HTTP 202(已接受)返回給用戶,否則返回 HTTP 200(確定)。
根據我在 FastAPI 文檔上的閱讀,調用 BackgroundTask 的方法是通過另一個 API。
現在我想要做的是,保持后台任務運行(如 cronjob),輪詢 SQS 隊列中的消息,處理這些事件並刪除它們。 (這部分不應依賴於 API 調用)我想最好在 FastAPI 項目中執行此操作。
閱讀 FastAPI 文檔並沒有為我提供足夠的信息來實現它。 我還嘗試使用__init__.py
文件調用一個基本的后台作業(打印日期時間),但它控制了 FastAPI 進程並且 API 變得不可用。
有兩種方法可以實現這一點
async
和await
function 正如您所提到的,您想要原生 FAST API 中的某些東西,那么我認為最好使用async
,然后像下面這樣等待
async def get_event_done(event: list):
# Do some asynchronous stuff to process the event
return "event processed"
現在讓我們使用上面的 function 和 python 內置庫asyncio
futures = [get_event_done(event1), get_event_done(event2)]
event1_result,event_2_result = await asyncio.gather(*futures)
print("event 1 result", event1_result)
print("event 2 result", event2_result)
使用asyncio.gather
收集結果非常簡單和聰明
進一步參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.