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="[email protected]", 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

相关推荐
掘金-我是哪吒3 小时前
分布式微服务系统架构第131集:fastapi-python
分布式·python·微服务·系统架构·fastapi
Anesthesia丶2 天前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
weixin_307779133 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
掘金-我是哪吒3 天前
分布式微服务系统架构第130集:Python工程化FastAPI,运维Nginx-keepalived+Nginx实现高可用集群
运维·分布式·微服务·系统架构·fastapi
LingRannn3 天前
JWT的介绍与在Fastapi框架中的应用
fastapi
Python私教3 天前
使用FastAPI和React以及MongoDB构建全栈Web应用05 FastAPI快速入门
前端·react.js·fastapi
Python私教4 天前
全栈开发实战:FastAPI + React + MongoDB 构建现代Web应用
前端·react.js·fastapi
weixin_307779134 天前
使用FastAPI和Apache Flink构建跨环境数据管道
redis·python·云计算·fastapi·aws
真智AI7 天前
构建安全的机器学习推理API:基于FastAPI的用户认证与管理实战
安全·机器学习·fastapi
Data 实验室10 天前
爬虫管理平台-最新版本发布
开发语言·爬虫·python·fastapi