fastapi_get_headers.py
· 318 B · Python
Surowy
from fastapi import FastAPI, Header, Depends, HTTPException
from fastapi import Request
app = FastAPI()
@app.get("/headers")
async def get_headers(request: Request):
headers = dict(request.headers)
return {"headers": headers}
# 測試:
# curl -H "Custom-Header: test_value" http://127.0.0.1:8000/headers
| 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 | |
| 14 |
fastapi_protected_resource.py
· 498 B · Python
Surowy
from fastapi import FastAPI, Header, Depends, HTTPException
app = FastAPI()
def verify_token(api_key: str = Header(None)):
if api_key != "my_secure_token":
raise HTTPException(status_code=403, detail="存取被拒絕")
return api_key
@app.get("/protected-resource")
async def protected_resource(token: str = Depends(verify_token)):
return {"message": "驗證成功", "token": token}
# 測試:
# curl -H "api-key: my_secure_token" http://127.0.0.1:8000/protected-resource
| 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 | |
| 17 |
fastapi_secure_data.py
· 436 B · Python
Surowy
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
@app.get("/secure-data")
async def secure_data(api_key: str = Header(None)):
if api_key != "my_secure_token":
raise HTTPException(status_code=401, detail="無效的 API 金鑰")
return {"message": "驗證成功,提供安全數據"}
# 啟動伺服器後,使用 cURL 測試:
# curl -H "api-key: my_secure_token" http://127.0.0.1:8000/secure-data
| 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 |
| 13 |