如何使用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规范实际上需要一个字段grant_typepassword的值,但OAuth2PasswordRequestForm没有强制执行它。

如果需要强制执行,请改用OAuth2PasswordRequestFormStrict的OAuth2PasswordRequestForm。

因此,您的表单应该与下面的表单类似。grant_type="password"表示您正在向/token端点发送用户名和密码(也可以看看这个答案(。

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

最新更新