from fastapi import FastAPI,Depends
from typing import Optional
import uvicorn
app = FastAPI()
# 函数依赖注入方法
def page_index_size(page_index:Optional[int] = 1,page_size:Optional[int]=10):
return {
'page_index': page_index,
'page_size': page_size
}
# 依赖注入
@app.get('/item')
async def item_data(page_info:dict=Depends(page_index_size)):
return {
'page_index':page_info.get('page_index'),
'page_size': page_info.get('page_size')
}
# 类依赖注入方法
class PageInfo:
def __init__(self,page_index:Optional[int]=1,page_size:Optional[int]=10):
self.page_index = page_index
self.page_size = page_size
@app.get('/items')
async def create_page(page_info:PageInfo=Depends(PageInfo)):
return {
'page_index': page_info.page_index,
'page_size': page_info.page_size
}
# 类依赖注入省略写方法
class PageInfo1:
def __init__(self,page_index:Optional[int]=1,page_size:Optional[int]=10):
self.page_index = page_index
self.page_size = page_size
@app.get('/goods')
async def create_page1(page_info:PageInfo1=Depends()):
return {
'page_index': page_info.page_index,
'page_size': page_info.page_size,
}
# 三级联动注入用法
# 函数依赖注入方法
def total_page(total_pages:Optional[int]=10):
return total_pages
def page_index_size1(page_index:Optional[int] = 1,page_size:Optional[int]=10,total:Optional[int] = Depends(total_page)):
return {
'page_index': page_index,
'page_size': page_size,
'total':total
}
# 依赖注入
@app.get('/itemUser')
async def item_data1(page_info:dict=Depends(page_index_size1)):
return {
'page_index':page_info.get('page_index'),
'page_size': page_info.get('page_size'),
'total':page_info.get('total')
}
if __name__ == '__main__':
uvicorn.run('main:app',port=10001,reload=True)
fastapi依赖注入,非常重要,项目使用地方token验证
最新推荐文章于 2024-09-09 00:00:00 发布