Utoljára aktív 9 months ago

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

Revízió f16ced358b0ff492ead95c7c66200831d57c1e14

fastapi_get_headers.py Eredeti
1from fastapi import FastAPI, Header, Depends, HTTPException
2from fastapi import Request
3
4app = FastAPI()
5
6@app.get("/headers")
7async 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
14
fastapi_protected_resource.py Eredeti
1from fastapi import FastAPI, Header, Depends, HTTPException
2
3app = FastAPI()
4
5def 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")
11async 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
17
fastapi_secure_data.py Eredeti
1from fastapi import FastAPI, Header, HTTPException
2
3app = FastAPI()
4
5@app.get("/secure-data")
6async 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
13