我正在尝试遵循 Sanjeev 的 python API 开发教程 (https://www.youtube.com/watch?v=0sOvCWFmrtA 1)。直到 7.5 小时我才遇到任何麻烦,但现在我尝试在邮递员中创建一个新帖子,使用 JWT 令牌作为身份验证。当我尝试这样做时,我收到此错误:
“pydantic_core._pydantic_core.ValidationError:TokenData 的 1 个验证错误 ID 输入应该是有效的字符串 [type=string_type, input_value=14, input_type=int]”
我很确定我已经按照教程进行操作并且令牌是一个字符串,所以我不知道哪里出了问题。我会尝试提供所有相关代码,但如果您缺少某些内容,请告诉我。
来自 schemas.py:
class TokenData(BaseModel):
id: Optional[str]
来自oauth2.py:
from jose import JWTError, jwt
from datetime import datetime, timedelta
from . import schemas
from fastapi import Depends, status, HTTPException
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='login')
SECRET_KEY = "b8b33abbff04e43b4a43aed2ab1cc44e962d236caee378dcccce9dc46a3a5592"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_access_token(token: str, credentials_exception):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
id: str = payload.get("user_id")
if id is None:
raise credentials_exception
token_data = schemas.TokenData(id=id)
except JWTError:
raise credentials_exception
return token_data
def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f'Could not validate credentials', headers={'WWW-Authenticate': 'bearer'})
return verify_access_token(token, credentials_exception)
来自post.py:
@router.post("/", status_code=status.HTTP_201_CREATED, response_model=schemas.Post)
def create_post(post: schemas.PostCreate, db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)):
print(user_id)
new_post = models.Post(**post.model_dump())
db.add(new_post)
db.commit()
db.refresh(new_post)
return new_post
我尝试在几个值后面添加“:str”,但它不会改变结果。
您可以调整代码以获取令牌数据的字符串。像这样:
def verify_access_token(令牌:str,credentials_exception):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
id: str = payload.get("user_id")
if id is None:
raise credentials_exception
token_data = schemas.TokenData(id=str(id))
except JWTError:
raise credentials_exception
return token_data