代码拉取完成,页面将自动刷新
同步操作将从 尹煜/FastAPI_Study_Yinyu 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。