FastAPI - 安全(Security)4

删除routers/member.py文件

修改main.py文件

复制代码
# -*- coding:utf-8 --*-
from fastapi import Depends,FastAPI

from fastapi.security import OAuth2PasswordBearer
from typing import Annotated

oauth2_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, FastAPI

from fastapi.security import OAuth2PasswordBearer
from typing import Annotated
from pydantic import BaseModel

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    disabled: bool | None = None


def 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 user

app = 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

相关推荐
the局外人3 小时前
学习 FastAPI 的 Day 3:企业级目录与数据库迁移
后端·python·fastapi
梦因you而美21 小时前
LangChain-ReAct-Agent 智能客服系统 · 项目技术文档
langchain·agent·fastapi·扫地机器人·langgraph·rag 检索增强·react 智能客服
jsjzsl21 天前
独立自由度框架下位置自由度的本体论特征、物理现象与新技术路径
python·flask·fastapi
嘻哈baby1 天前
FastAPI + SQLite 从 0 写一个真正能用的待办 API
数据库·sqlite·fastapi
陈驰_05041 天前
需求列表接口 422 Unprocessable Entity 排查与修复全记录
状态模式·fastapi·vue 3
Json____1 天前
基于 FastAPI + Vue3 的在线拍卖系统技术解析
spring boot·后端·fastapi·wwwoop.com
创新技术阁1 天前
FastapiAdmin 实战:二次开发前的准备(环境配置与项目启动)
前端·后端·fastapi
神秘的猪头2 天前
新版 LangChain Agent 核心架构:State、Context、ToolRuntime 与 Middleware
langchain·llm·fastapi
神秘的猪头2 天前
新版 LangChain Agent 入门:从 `bind_tools + while` 到 `create_agent`
langchain·fastapi
神秘的猪头2 天前
把新版 LangChain Agent 做成真正应用:Memory、Streaming、SSE 与 Structured Output
langchain·fastapi