在FastAPI通过标注Header类型获取Authorization时, 会导致openapi页面的请求没法使用
from typing import Annotated
from fastapi import FastAPI, Header, Request, Depends, Cookie, Query, APIRouter
from fastapi.routing import APIRoute
from fastapi.security.api_key import APIKeyCookie, APIKeyHeader, APIKeyQuery
from fastapi.openapi.models import SecuritySchemeType
app = FastAPI()
@app.get("/get_key")
def get_api_key(
request: Request,
authorization: Annotated[str, Header()],
):
print(authorization)
print(request.headers)
return "OK"
这是因为openapi发请求时会过滤掉token的字段, 导致fastapi报错
为了解决这个问题fastapi把认证相关的逻辑放到了fastapi.security.api_key模块,通过Depends的方式来解决的.
from typing import Annotated
from fastapi import FastAPI, Header, Request, Depends, Cookie, Query, APIRouter
from fastapi.routing import APIRoute
from fastapi.security.api_key import APIKeyCookie, APIKeyHeader, APIKeyQuery
from fastapi.openapi.models import SecuritySchemeType
app = FastAPI()
@app.get("/get_key")
def get_api_key(
request: Request,
authorization: Annotated[str,
Depends(APIKeyHeader(name="authorization"))],
):
print(authorization)
print(request.headers)
return "OK"
这样就解决了!
标签:get,fastapi,获取,token,api,key,FastAPI,import From: https://www.cnblogs.com/houchuanqi/p/18186383