删除routers/member.py
文件
修改main.py
文件
# -*- coding:utf-8 –*-
from fastapi import Depends,FastAPIfrom fastapi.security import OAuth2PasswordBearer
from typing import Annotatedoauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")app = FastAPI(title="文档标题",description="关于API文档的补充说明",version="1.0.0",docs_url="/docs"
)@app.get("/items/")
async def read_items(token: Annotated[str, Depends(oauth2_scheme)]):return {"token": token}
https://fastapi.tiangolo.com/zh/tutorial/security/first-steps
创建用户模型
修改main.py
文件
# -*- coding:utf-8 –*-
from fastapi import Depends, FastAPIfrom fastapi.security import OAuth2PasswordBearer
from typing import Annotated
from pydantic import BaseModeloauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")class User(BaseModel):username: stremail: str | None = Nonefull_name: str | None = Nonedisabled: bool | None = Nonedef fake_decode_token(token):return User(username=token + "fakedecoded", email="vvv@example.com", full_name="vvv lao")async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):user = fake_decode_token(token)return userapp = FastAPI(title="文档标题",description="关于API文档的补充说明",version="1.0.0",docs_url="/docs"
)@app.get("/users/me")
async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]):return current_user
其中get_current_user
使用oauth2_scheme
作为依赖项
https://fastapi.tiangolo.com/zh/tutorial/security/simple-oauth2