Расширение FastAPI OAuth2PasswordRequestForm
Понадобились дополнительные поля в форме OAuth2PasswordRequestForm. Пробовал различные варианты, однако добиться нужного результата не смог.
Код:
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import BaseModel
app = FastAPI()
class UserBaseScheme(BaseModel):
email: str
username: str
first_name: str | None
second_name: str | None
class UserCreateScheme(UserBaseScheme):
password: str
class OAuth2ExtendedFormManual(OAuth2PasswordRequestForm):
email: str
class OAuth2ExtendedFormGrantType(OAuth2PasswordRequestForm):
email: str
grant_type: str
class OAuth2ExtendedFormInherit(OAuth2PasswordRequestForm,
UserCreateScheme):
pass
"""
Trying to send this as a form-data to all routes:
1. {'username': 'boo', 'password': 'boo', 'email': '[email protected]}
2. {'username': 'boo', 'password': 'boo', 'email': '[email protected], 'grant_type': 'password'}
In both cases I can't get the expected result.
"""
@app.post("/sign-up-standard/")
async def sign_up(form_data: OAuth2PasswordRequestForm = Depends()):
print(form_data.__dict__)
# 1, 2 -> {
# 'grant_type': None | 'password',
# 'username': 'boo',
# 'password': 'boo',
# 'scopes': [],
# 'client_id': None,
# 'client_secret': None
# }
# Where is an email field?
@app.post("/sign-up-extended-manual/")
async def sign_up(form_data: OAuth2ExtendedFormManual = Depends()):
print(form_data.__dict__)
# 1, 2 -> {
# 'grant_type': None | 'password',
# 'username': 'boo',
# 'password': 'boo',
# 'scopes': [],
# 'client_id': None,
# 'client_secret': None
# }
# Where is an email field?
@app.post("/sign-up-extended-manual-grant-type/")
async def sign_up(form_data: OAuth2ExtendedFormGrantType = Depends()):
print(form_data.__dict__)
# 1, 2 -> {
# 'grant_type': None | 'password',
# 'username': 'boo',
# 'password': 'boo',
# 'scopes': [],
# 'client_id': None,
# 'client_secret': None
# }
# Where is an email field?
@app.post("/sign-up-extended-inherit/")
async def sign_up(form_data: OAuth2ExtendedFormInherit = Depends()):
print(form_data.__dict__)
# 1, 2 -> File "pydantic\main.py", line 358, in pydantic.main.BaseModel.__setattr__
# ValueError: "OAuth2ExtendedFormInherit" object has no field "grant_type"
Не знаю, насколько хорошая идея смешивать Pydantic модель и форму, однако добавление полей вручную также не работает.
Отправлять форму пытался как с grant_type, так и без него, нулевой результат в обоих случаях.