- FastAPI 教程
- FastAPI - 首頁
- FastAPI - 簡介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 型別提示
- FastAPI - IDE 支援
- FastAPI - REST 架構
- FastAPI - 路徑引數
- FastAPI - 查詢引數
- FastAPI - 引數驗證
- FastAPI - Pydantic
- FastAPI - 請求體
- FastAPI - 模板
- FastAPI - 靜態檔案
- FastAPI - HTML 表單模板
- FastAPI - 訪問表單資料
- FastAPI - 上傳檔案
- FastAPI - Cookie 引數
- FastAPI - 頭部引數
- FastAPI - 響應模型
- FastAPI - 巢狀模型
- FastAPI - 依賴項
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 資料庫
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - WebSockets
- FastAPI - 事件處理器
- FastAPI - 掛載子應用
- FastAPI - 中介軟體
- FastAPI - 掛載 Flask 應用
- FastAPI - 部署
- FastAPI 有用資源
- FastAPI - 快速指南
- FastAPI - 有用資源
- FastAPI - 討論
FastAPI - 事件處理器
事件處理器是在發生特定已識別事件時要執行的函式。在 FastAPI 中,已識別兩個此類事件- 啟動和關閉。FastAPI 的應用程式物件具有on_event()裝飾器,它使用這些事件之一作為引數。使用此裝飾器註冊的函式在發生相應的事件時觸發。
啟動事件發生在開發伺服器啟動之前,註冊的函式通常用於執行某些初始化任務,例如建立與資料庫的連線等。關閉事件的事件處理器在應用程式關閉之前立即呼叫。
示例
這是一個啟動和關閉事件處理器的簡單示例。當應用程式啟動時,啟動時間會在控制檯日誌中回顯。類似地,當透過按 ctrl+c 停止伺服器時,也會顯示關閉時間。
main.py
from fastapi import FastAPI
import datetime
app = FastAPI()
@app.on_event("startup")
async def startup_event():
print('Server started :', datetime.datetime.now())
@app.on_event("shutdown")
async def shutdown_event():
print('server Shutdown :', datetime.datetime.now())
輸出
它將產生以下輸出:
uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [28720] INFO: Started server process [28722] INFO: Waiting for application startup. Server started: 2021-11-23 23:51:45.907691 INFO: Application startup complete. INFO: Shutting down INFO: Waiting for application server Shutdown: 2021-11-23 23:51:50.82955 INFO: Application shutdown com INFO: Finished server process
廣告