fastapi get header parameter is none in basemodel use Header cant get token but in function its ok 为什么?

fastapi get header parameter is none in basemodel use Header cant get token but in function its ok why?

在 basemodel 中使用 Header 无法获取令牌,但在功能中它可以,为什么?

   class Test(BaseModel):
        name: str
        token: str= Header(None)

def login(t: Test):
    print(t.dict())
    return 'test'

output  {'name': '123', 'token': None} 

如果我这样做就可以了

def login(t: Test,token: str= Header(None)):
        print(t.dict(),token)
        return 'test'
    
    output  {'name': '123', 'token': None} 123456

谁能帮帮我!

这里的 Pydantic 模型表示对请求负载的验证。

“测试”模型中提到的值应该在请求负载中可用。由于 header 不是负载,我们不能在 Basemodel 中使用它。

但您可以在 api 函数中使用它。当您调用 api 时,请求参数可以在函数中使用。所以,可以使用这个