【问题标题】:make Depends optional in fastapi python在 fastapi python 中使 Depends 成为可选
【发布时间】:2021-05-31 22:00:28
【问题描述】:

我有一个向用户和非用户提供图像的 API。图片可以是公开的也可以是私有的。

我的代码

@router.get("/{id}")
def get_resource(id: str, current_user: User = Depends(get_current_user)):
  return return_resource(id, current_user)

此代码严格执行授权。我想如果用户没有登录,那么它应该把None 放在current_user 中,这样我就可以允许访问公共图像并限制私有。

其他代码

get_current_user

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")

async def get_current_user(required: bool = True, token: str = Depends(oauth2_scheme)):
  credentials_exception = HTTPException(
    status_code=status.HTTP_401_UNAUTHORIZED,
    detail="Could not validate credentials",
    headers={"WWW-Authenticate": "Bearer"},
  )

  if not required and not token:
    return None

  return verify_token(token, credentials_exception)

我想将required之类的参数发送到get_current_user

验证令牌

def verify_token(token: str, credentials_exception):
  try:
    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    email: str = payload.get("email")
    pk: str = payload.get("pk")
    if email is None:
        raise credentials_exception
    token_data = TokenData(
        email=email,
        pk = pk
    )
  except JWTError:
      raise credentials_exception
  return token_data

【问题讨论】:

    标签: python oauth-2.0 fastapi


    【解决方案1】:

    如果我理解正确,您可以使用包装函数将参数传递给嵌套函数。像这样:

    def get_current_user(required: bool = True):
        async def _get_user(token: str = Depends(oauth2_scheme)):
            credentials_exception = HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Could not validate credentials",
                headers={"WWW-Authenticate": "Bearer"},
            )
    
            if not required and not token:
                return None
    
            return verify_token(token, credentials_exception)
    
        return _get_user
    
    
    
    @router.get("/{id}")
    def get_resource(id: str, current_user: User = Depends(get_current_user(False))):
      return return_resource(id, current_user)
    

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 2021-03-22
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多