FastAPI 是一个现代、快速(高性能)的 web 框架,用于构建 API,基于 Python 3.7+ 的类型提示。当遇到 422 错误时,通常是因为客户端发送的数据无法通过服务器端的验证。
原因:客户端发送的数据不符合 Pydantic 模型的定义。
解决方案:
@app.post
装饰器中的 response_model
参数来指定响应模型,以确保返回的数据格式正确。from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
email: str
@app.post("/users/", response_model=User)
async def create_user(user: User):
# 假设这里有一些逻辑来处理用户创建
return user
原因:未正确实现或配置身份验证机制。
解决方案:
fastapi.security
模块中的 HTTPBearer
或 OAuth2PasswordBearer
。from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
# 这里可以添加从数据库获取用户的逻辑
return {"username": username}
@app.post("/users/me/", response_model=User)
async def read_users_me(current_user: dict = Depends(get_current_user)):
return current_user
领取专属 10元无门槛券
手把手带您无忧上云