我正在通过fastapi中的jwt进行用户登录,对于登录,我在swagger
中得到了这样的信息
我不知道为什么会出现这个local_kw表单字段,这是我的端点代码
from sqlalchemy.orm import sessionmaker
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
@router.post("/token", response_model=dict)
async def login_for_access_token(
login_data: LoginRequestBody,
session: Session = Depends(SessionLocal)
):
user = (
session.query(User)
.filter(
or_(
User.username == login_data.email_or_phone_number,
User.email == login_data.email_or_phone_number,
User.phone_number == login_data.email_or_phone_number,
)
)
.first()
)
if user and verify_password(login_data.password, user.hashed_password):
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_jwt_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
refresh_token_expires = timedelta(days=1)
refresh_token = create_jwt_token(
data={"sub": user.username, "scope": "refresh"},
expires_delta=refresh_token_expires,
)
output_response = {
"detail": {
"status": "success",
"message": "Login successful",
"access_token": access_token,
"refresh_token": refresh_token,
}
}
return JSONResponse(status_code=200, content=output_response)
# Handle other error scenarios
error_response = {
"detail": {
"status": "fail",
"message": "The application has encountered an unknown error. It doesn't appear to have affected your data, but our technical staff have been automatically notified and will be looking into this with the utmost urgency.",
}
}
return JSONResponse(status_code=400, content=error_response)
字符串
我只想local_kw字段消失,我正在使用这些包
- python==3.10.13
- fastapi==0.105.0
- SQLAlchemy==2.0.23
- Uvicorn==0.24.0.post1
- 证书==2023.7.22
2条答案
按热度按时间ercv8c1e1#
问题是
SessionLocal
类(或函数)需要local_pw
作为可选参数。FastAPI试图从Query
参数中获取此参数的值。为了避免这种情况,您可以创建如下所示的
get_session_local
函数,并将此新函数用作端点的依赖项。字符串
我建议您使用这种方法,而不是直接在端点中调用
SessionLocal()
。在这个实现中,您将来仍然有可能使用override this dependency。
oaxa6hgo2#
感谢Yurii_Motov,我能够修改代码如下,现在它像预期的那样工作。
字符串