您的位置:首页 > 健康 > 养生 > FastAPI - 安全(Security)4

FastAPI - 安全(Security)4

2024/12/29 0:13:30 来源:https://blog.csdn.net/buyueliuying/article/details/139328911  浏览:    关键词:FastAPI - 安全(Security)4

删除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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com