我想在快速 api 中更改 api 响应 json |虚张声势的
I want to change api response json in fastapi | pydantic
我是fastapi的新手,请帮助我!
当我在 fastAPI 中使用 response_model 时,更改默认 API 响应时出现验证错误。
默认 API 响应很简单 json 就像来自 response_model 的对象。
user.py
from fastapi import FastAPI, Response, status, HTTPException, Depends
from sqlalchemy.orm.session import Session
import models
import schemas
from database import get_db
app = FastAPI()
@app.post('/', response_model=schemas.UserOut)
def UserCreate(users:schemas.UserBase, db:Session = Depends(get_db)):
# print(db.query(models.User).filter(models.User.username == users.username).first().username)
if db.query(models.User).filter(models.User.email == users.email).first() != None:
if users.email == db.query(models.User).filter(models.User.email == users.email).first().email:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="email already exist")
hashed_password = hash(users.password)
users.password =hashed_password
new_user = models.User(**users.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
# return new_user #if i uncomment this code then it will give default response which i don't want
return {"status":True,"data":new_user, "message":"User Created Successfully"}
schemas.py
from pydantic import BaseModel, validator, ValidationError
from datetime import datetime
from typing import Optional, Text
from pydantic.networks import EmailStr
from pydantic.types import constr, conint
class UserBase(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: constr(min_length=10, max_length=10)
password: str
class UserOut(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: str
class Config:
orm_mode = True
现在,当我 运行 这段代码时,它会给我如下所述的错误。
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 243, in app
is_coroutine=is_coroutine,
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 137, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 7 validation errors for UserOut
response -> name
field required (type=value_error.missing)
response -> email
field required (type=value_error.missing)
response -> country
field required (type=value_error.missing)
response -> city
field required (type=value_error.missing)
response -> state
field required (type=value_error.missing)
response -> address
field required (type=value_error.missing)
response -> phone
field required (type=value_error.missing)
下面是我想要的输出:-
{
"status": true,
"data": {
"name": "raj",
"email": "rajshah123@gmail.com",
"country": "India",
"city": "surat",
"state": "gujarat",
"address": "str5654",
"phone": "6666888899"
},
"message": "User Created Successfully"
}
非常感谢。
json你return的型号一定要匹配。在你的情况下它没有。您的模型必须看起来像
class YourModel(BaseModel):
status : bool
data : UserOut
message: str
您返回的对象与您的 response_model 不匹配。您有两个选择:
最后一行应该是return new_user
而不是return {"status":True,"data":new_user, "message":"User Created Successfully"}
你 response_model 应该是这样的:
class UserOutSchema(BaseModel):
user: UserOut
status: str
message: str
我是fastapi的新手,请帮助我!
当我在 fastAPI 中使用 response_model 时,更改默认 API 响应时出现验证错误。
默认 API 响应很简单 json 就像来自 response_model 的对象。
user.py
from fastapi import FastAPI, Response, status, HTTPException, Depends
from sqlalchemy.orm.session import Session
import models
import schemas
from database import get_db
app = FastAPI()
@app.post('/', response_model=schemas.UserOut)
def UserCreate(users:schemas.UserBase, db:Session = Depends(get_db)):
# print(db.query(models.User).filter(models.User.username == users.username).first().username)
if db.query(models.User).filter(models.User.email == users.email).first() != None:
if users.email == db.query(models.User).filter(models.User.email == users.email).first().email:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="email already exist")
hashed_password = hash(users.password)
users.password =hashed_password
new_user = models.User(**users.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
# return new_user #if i uncomment this code then it will give default response which i don't want
return {"status":True,"data":new_user, "message":"User Created Successfully"}
schemas.py
from pydantic import BaseModel, validator, ValidationError
from datetime import datetime
from typing import Optional, Text
from pydantic.networks import EmailStr
from pydantic.types import constr, conint
class UserBase(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: constr(min_length=10, max_length=10)
password: str
class UserOut(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: str
class Config:
orm_mode = True
现在,当我 运行 这段代码时,它会给我如下所述的错误。
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 243, in app
is_coroutine=is_coroutine,
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 137, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 7 validation errors for UserOut
response -> name
field required (type=value_error.missing)
response -> email
field required (type=value_error.missing)
response -> country
field required (type=value_error.missing)
response -> city
field required (type=value_error.missing)
response -> state
field required (type=value_error.missing)
response -> address
field required (type=value_error.missing)
response -> phone
field required (type=value_error.missing)
下面是我想要的输出:-
{
"status": true,
"data": {
"name": "raj",
"email": "rajshah123@gmail.com",
"country": "India",
"city": "surat",
"state": "gujarat",
"address": "str5654",
"phone": "6666888899"
},
"message": "User Created Successfully"
}
非常感谢。
json你return的型号一定要匹配。在你的情况下它没有。您的模型必须看起来像
class YourModel(BaseModel):
status : bool
data : UserOut
message: str
您返回的对象与您的 response_model 不匹配。您有两个选择:
最后一行应该是
return new_user
而不是return {"status":True,"data":new_user, "message":"User Created Successfully"}
你 response_model 应该是这样的:
class UserOutSchema(BaseModel): user: UserOut status: str message: str