对于
FastAPI
来说相对较新,我正在尝试执行一个小项目。已阅读 https://fastapi.tiangolo.com/ 中的示例。并确实得到了我发布的一些内容,但不是全部。
我的帖子是一个 JSON 正文,具有单个标头,但使用基本身份验证。如果我使用
FastAPI
基本 Auth
示例,我可以轻松获得 user/pass
。如果我使用 Request,它可以轻松获取 Header 和 Body,但访问用户数据却很困难
), "AuthenticationMiddleware must be installed to access request.user"
AssertionError: AuthenticationMiddleware must be installed to access request.user
所以我可以看到它在那里,但无法读取。
from typing import Union
from fastapi import Depends, FastAPI, Header, Request, Body
from fastapi.security import HTTPBasic, HTTPBasicCredentials
security = HTTPBasic()
app = FastAPI()
@app.post("/posttest")
async def root(request: Request):
my_header = request.headers.get('client_id')
return{"Client-Id": my_header, "Body": await request.json(), "User": request.user}
我不确定如何收集所有 3 位,因此我可以使用自己的 python 请求代码对这些数据进行正确的
O-Auth2
调用,以返回原始帖子所需的答案(该应用程序无法做到 O-Auth
,所以我正在做一个楔子)
此块将获取用户名和密码,但我无法提取我的标题或正文。我确信我错过了一些愚蠢的东西,但这是我第一次尝试。
async def root(credentials: HTTPBasicCredentials = Depends(security)):
return {"username": credentials.username, "password": credentials.password}
通过学习如何将属性构建到我的应用程序功能中来了解我的解决方案。谢谢大家!
def read_items(
credentials: HTTPBasicCredentials = Depends(security),
client_id: Union[str, None] = Header(default=None, convert_underscores=False),
item: str = Body(embed=True)
):