大家晚上好。我正在尝试使用FastAPI向我的数据库添加新用户。当我尝试通过python控制台应用程序执行此操作时,FastAPI显示以下消息:
{
'detail': [
{
'loc': ['body', 'nickname'],
'msg': 'field required',
'type': 'value_error.missing'
},
{
'loc': ['body', 'password'],
'msg': 'field required',
'type': 'value_error.missing'
},
{
'loc': ['body', 'email'],
'msg': 'field required',
'type': 'value_error.missing'
}
]
}
但是当我在/docs
中执行这个请求时,一切都正常了!
下面是我的pydantic模型:
class GetUserModel(BaseModel):
nickname: str
password: str
email: str
class Config:
orm_mode = True
这是我的联络人
@users_router.post("/users/", status_code=200)
def add_new_user(user: GetUserModel, session: Session = Depends(get_session)):
user.password = bcrypt.hashpw(
user.password.encode(),
bcrypt.gensalt()
) # password hashing
new_user = User(**user.dict())
add(session, new_user) # adding to database
在这里我试着提出一个请求:
response = requests.post(
'http://127.0.0.1:8000/users/',
data={
"nickname": "1",
"password": "1",
"email": "1"
})
print(response.json())
如果你知道有什么问题,请告诉我,我将不胜感激!
1条答案
按热度按时间sczxawaw1#
根据对您的问题的评论,为了使您的请求生效,您需要使用
json
参数执行request
,因为使用data
FastAPI时假定您正在发送表单数据:但是,如果您确实想发送表单数据,则需要更改端点以接受
Form
参数: