FastAPI 学习之路(二十六)全局依赖项

简介: FastAPI 学习之路(二十六)全局依赖项

有时,我们要为整个应用添加依赖项。通过与定义FastAPI 学习之路(二十五)路径操作装饰器依赖项


类似的方式,可以把依赖项添加至整个 FastAPI 应用。


       那么我们看下,如何去实现,比如我们全局都需要校验token。我们去看下,我们应该如何实现代码。


from fastapi import  FastAPI,Header, HTTPException,Depends
fake_items_db = [{"city": "beijing"}, {"city": "shanghai"},
                 {"city": "heze"}]
def verify_token(token: str = Header(...)):
    if token!="leizishuoceshikaifa":
        raise HTTPException(status_code=400, detail="Token header invalid")
app = FastAPI(dependencies=[Depends(verify_token)])
@app.get("/items/")
def read_items():
    return fake_items_db
@app.get("/item/")
def read_item(city:str):
    for item in fake_items_db:
        if item['city']==city:
            return item
    return {"msg":"not exict"}


那么我们看下,接口是否都需要token。


测试items


image.png


我们增加下token


image.png


我们去测试下带参数


image.png


我们带下token


image.png

相关文章
|
Python
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器
261 0
FastAPI(33)- Global Dependencies 全局依赖
FastAPI(33)- Global Dependencies 全局依赖
299 0
FastAPI(33)- Global Dependencies 全局依赖
FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖
FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖
141 0
FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖
|
缓存 API
FastAPI(31)- Sub-dependencies 子依赖
FastAPI(31)- Sub-dependencies 子依赖
120 0
FastAPI(31)- Sub-dependencies 子依赖
|
NoSQL 测试技术 Redis
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(下)
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(下)
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(下)
|
测试技术 数据安全/隐私保护
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(上)
FastAPI(八十四)实战开发《在线课程学习系统》--接口测试(上)
|
存储 测试技术 数据安全/隐私保护
FastAPI(八十三)实战开发《在线课程学习系统》--注册接口单元测试
FastAPI(八十三)实战开发《在线课程学习系统》--注册接口单元测试
FastAPI(八十三)实战开发《在线课程学习系统》--注册接口单元测试
FastAPI(八十二)实战开发《在线课程学习系统》接口开发-- 课程上架下架
FastAPI(八十二)实战开发《在线课程学习系统》接口开发-- 课程上架下架
|
NoSQL Redis 数据库
FastAPI(八十一)实战开发《在线课程学习系统》接口开发-- 推荐课程列表与课程点赞
FastAPI(八十一)实战开发《在线课程学习系统》接口开发-- 推荐课程列表与课程点赞
FastAPI(八十)实战开发《在线课程学习系统》接口开发-- 课程列表
FastAPI(八十)实战开发《在线课程学习系统》接口开发-- 课程列表