加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
7_depends.py 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
尹煜 提交于 2023-06-04 13:01 . 7章内容
from typing import Union
from fastapi import Depends, FastAPI, HTTPException, Cookie, Header
app = FastAPI()
'''
1.2 demo
'''
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return commons
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
'''
2.1 类作为依赖项
'''
class CommonQueryParams:
def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items2/")
async def read_items(commons = Depends(CommonQueryParams)):
return commons
'''
2.2 嵌套依赖项
'''
def query_extractor(q: Union[str, None] = None):
return q
def query_or_cookie_extractor(
q: str = Depends(query_extractor),
last_query: Union[str, None] = Cookie(default=None),
):
if not q:
return last_query
return q
@app.get("/items3/")
async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)):
return {"q_or_cookie": query_or_default}
'''
2.3 dependencies 参数
'''
async def verify_token(x_token: str = Header()):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
async def verify_key(x_key: str = Header()):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")
return x_key
@app.get("/items4/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
return [{"item": "Foo"}, {"item": "Bar"}]
'''
2.4 全局依赖项
'''
app1 = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
@app1.get("/items5/")
async def read_items():
return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化