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

相关推荐
曲幽12 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽3 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤4 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽4 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
百锦再5 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
Li emily6 天前
解决了股票实时数据接口延迟问题
人工智能·fastapi
司徒轩宇6 天前
FastAPI + Uvicorn 深度理解与异步模型解析
fastapi
郝学胜-神的一滴6 天前
FastAPI:Python 高性能 Web 框架的优雅之选
开发语言·前端·数据结构·python·算法·fastapi