python 如何在FastAPI中间件中更改Header?

lyfkaqu1  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(369)

我需要将授权头从令牌替换为屏障
范例

@app.middleware("https")
async def replace_prefix_token(request: Request, call_next):
    if "Authorization" in request.headers and request.headers["Authorization"].split()[0] == "Token":
        request.headers["Authorization"] = request.headers["Authorization"].replace("Token", "Bearer")
    response = await call_next(request)
    return response

误差

TypeError: 'Headers' object does not support item assignment
qco9c6ql

qco9c6ql1#

Headers本身是一个不可变的对象,但是你可以尝试使用update方法来修改header值:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.middleware("http")
async def replace_prefix_token(request: Request, call_next):
    if "Authorization" in request.headers and request.headers["Authorization"].split()[0] == "Token":
        request.headers.update({"Authorization": request.headers["Authorization"].replace("Token", "Bearer")})
    response = await call_next(request)
    return response

@app.get("/")
async def root():
    return JSONResponse(content={"message": "Hello, world!"})

相关问题