繁体   English   中英

如何使用 aiohttp 发布表单数据?

[英]How do I post Form Data with aiohttp?

我正在测试使用 FastAPI 制作 OAuth 服务器。 我有一个方面,即 Oauth 服务器,它的端点如下所示:

@router.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()) -> Dict[str, str]:
    return {"access_token": form_data.username, "token_type": "bearer"}

然后在一个单独的过程中,我有一个带有登录端点的假应用程序,如下所示:

@router.post("/")
async def login(username: str, password: str) -> Dict[str, str]:

    form = OAuth2PasswordRequestForm(
        username=username,
        password=password,
        scope="me"
    )

    form_data = aiohttp.FormData()

    for key, val in form.__dict__.items():
        form_data.add_field(key, val)

    async with aiohttp.ClientSession() as session:
        async with session.post(f"http://localhost:8001/oauth/token", data=form_data()) as server_response:
            response = await server_response.text()
            response = json.loads(response)
    return response

OAuth 服务器响应

{
  "detail": [
    {
      "loc": [
        "body",
        "grant_type"
      ],
      "msg": "string does not match regex \"password\"",
      "type": "value_error.str.regex",
      "ctx": {
        "pattern": "password"
      }
    }
  ]
}

如何使用 aiohttp 将表单数据发布到 oauth 服务器?

您的数据中缺少grant_type字段。 尽管根据文档grant_type是一个可选字段(请查看“提示”部分):

OAuth2 规范实际上需要一个带有固定值password的字段 grant_type ,但 OAuth2PasswordRequestForm 不强制它。

如果需要强制执行,请使用 OAuth2PasswordRequestFormStrict 而不是 OAuth2PasswordRequestForm。

因此,您的表单应如下所示。 grant_type="password"表示您正在向/token端点发送用户名和密码(也请查看此答案)。

form = OAuth2PasswordRequestForm(
    grant_type="password",
    username=username,
    password=password,
    scope="me"
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM