FastAPI学习笔记(一)-4.项目框架
一、项目框架
/run.py是入口文件。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import uvicorn 2 from fastapi import FastAPI 3 4 app = FastAPI() 5 6 # 启动命令: uvicorn run:app --reload 7 if __name__ == '__main__': 8 uvicorn.run('run:app', host='0.0.0.0', port=8000, reload=True, debug=True, workers=2)
通过代码启动app服务。
/tutorial/chapter03.py文件是每一章节的主文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ''' 2 @author:invoker 3 @project:fastapi202108 4 @file: chapter03.py 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/8/5 21:22 8 @version: Python 3.7.8 9 ''' 10 11 from fastapi import APIRouter 12 app03 = APIRouter() 13 14 """ 15 第三章 路径参数与数字验证 16 """ 17 18 @app03.get('/path/{parameters}') 19 async def path_param01(parameters:str): 20 return {"msg":parameters}
app03为路由对象
/tutorial/__init__.py 是tutorial的打包文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ''' 2 @author:invoker 3 @project:fastapi202108 4 @file: __init__.py.py 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/8/5 21:21 8 @version: Python 3.7.8 9 ''' 10 from .chapter03 import app03 11 # 将每个章节的app对象打包 12 from .chapter04 import app04
将.chapter03打包成app03
/run.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ''' 2 @author:invoker 3 @project:fastapi202108 4 @file: run.py 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/8/5 21:22 8 @version: Python 3.7.8 9 ''' 10 11 import uvicorn 12 from fastapi import FastAPI 13 from tutorial import app03,app04 14 15 app = FastAPI() 16 app.include_router(app03,prefix='/chapter03',tags=['第三章 请求参数和验证']) 17 # app.include_router(app04,prefix='/chapter04',tags=['第四章']) 18 19 # 启动命令: uvicorn run:app --reload 20 if __name__ == '__main__': 21 uvicorn.run('run:app', host='0.0.0.0', port=8000, reload=True, debug=True, workers=2)
导入app03后,在通过include_router来引用路由
运行run.py后
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/15106254.html