在 FastAPI 中,你可以通过在路径操作函数的参数中使用 Depends 来获取当前用户信息。通常,这涉及到使用身份验证机制(如 OAuth2)并使用依赖项来提取和验证用户的身份信息。

以下是一个基于 OAuth2 身份验证的例子,演示如何获取当前用户:
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

# 使用 OAuth2PasswordBearer 创建 OAuth2 依赖项
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# 模拟从数据库中获取用户信息的函数
def get_current_user(token: str = Depends(oauth2_scheme)):
    # 在实际应用中,这里可能需要解析和验证 token,并从数据库中获取用户信息
    if token != "fake-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"username": "fakeuser", "email": "fakeuser@example.com"}

# 路径操作函数中使用 get_current_user 依赖项来获取当前用户
@app.get("/users/me")
async def read_current_user(current_user: dict = Depends(get_current_user)):
    return current_user

在这个例子中:

  •  oauth2_scheme 是一个 OAuth2PasswordBearer 实例,它用于处理从请求中提取令牌。

  •  get_current_user 函数是一个依赖项,它依赖于 oauth2_scheme,并负责解析和验证令牌,然后返回包含用户信息的字典。

  •  在路径操作函数 read_current_user 中,我们声明了一个参数 current_user,它使用 Depends(get_current_user) 来获取当前用户信息。


在实际应用中,你需要根据你的身份验证机制(OAuth2、API 密钥等)来实现 get_current_user 函数,确保从令牌中提取并验证用户的身份信息。


转载请注明出处:http://www.pingtaimeng.com/article/detail/7391/FastAPI