Ostatnio aktywny 9 months ago

FastAPI 可透過 Header 讀取請求標頭,並透過 Depends 進行依賴注入(Dependency Injection),適用於 API Token 驗證、身份驗證、請求處理 等場景。

timmy zrewidował ten Gist 9 months ago. Przejdź do rewizji

3 files changed, 41 insertions

fastapi_get_headers.py(stworzono plik)

@@ -0,0 +1,13 @@
1 + from fastapi import FastAPI, Header, Depends, HTTPException
2 + from fastapi import Request
3 +
4 + app = FastAPI()
5 +
6 + @app.get("/headers")
7 + async def get_headers(request: Request):
8 + headers = dict(request.headers)
9 + return {"headers": headers}
10 +
11 + # 測試:
12 + # curl -H "Custom-Header: test_value" http://127.0.0.1:8000/headers
13 +

fastapi_protected_resource.py(stworzono plik)

@@ -0,0 +1,16 @@
1 + from fastapi import FastAPI, Header, Depends, HTTPException
2 +
3 + app = FastAPI()
4 +
5 + def verify_token(api_key: str = Header(None)):
6 + if api_key != "my_secure_token":
7 + raise HTTPException(status_code=403, detail="存取被拒絕")
8 + return api_key
9 +
10 + @app.get("/protected-resource")
11 + async def protected_resource(token: str = Depends(verify_token)):
12 + return {"message": "驗證成功", "token": token}
13 +
14 + # 測試:
15 + # curl -H "api-key: my_secure_token" http://127.0.0.1:8000/protected-resource
16 +

fastapi_secure_data.py(stworzono plik)

@@ -0,0 +1,12 @@
1 + from fastapi import FastAPI, Header, HTTPException
2 +
3 + app = FastAPI()
4 +
5 + @app.get("/secure-data")
6 + async def secure_data(api_key: str = Header(None)):
7 + if api_key != "my_secure_token":
8 + raise HTTPException(status_code=401, detail="無效的 API 金鑰")
9 + return {"message": "驗證成功,提供安全數據"}
10 +
11 + # 啟動伺服器後,使用 cURL 測試:
12 + # curl -H "api-key: my_secure_token" http://127.0.0.1:8000/secure-data
Nowsze Starsze