python3的uvicorn模块
FastAPI和uvicorn 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。
1、基本操作举例1:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import uvicorn from fastapi import FastAPI app = FastAPI() # 绑定路由和视图函数 @app.get("/") def index(): return {"msg": "fastapi测试成功"} # 异步 后面基本会用异步 速度快 @app.get("/A") async def A(): return {"msg": "异步请求成功"} # 同步 @app.get("/B") def B(): return {"msg": "请求成功"} ### 动态路径 和 Flask 不同,Flask 是使用 <>,而 FastAPI 使用 {} @app.get("/C/{item_id}") def C(item_id): return {"msg": item_id} if __name__ == "__main__": uvicorn.run(app,host="0.0.0.0",port=8000)
2、Uvicorn支持静态文件服务,默认情况下在项目根目录下public目录,可以在Uvicorn的运行参数中配置。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import uvicorn from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount("/", StaticFiles(directory="mirror"), name="mirror") if __name__ == "__main__": uvicorn.run(app,host="0.0.0.0",port=8000)
3、交互式文档
访问http://127.0.0.1:8000/docs 和 http://127.0.0.1:8000/redoc
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import uvicorn import asyncio from fastapi import FastAPI,applications from fastapi.openapi.docs import get_swagger_ui_html app = FastAPI() def swagger_monkey_patch(*args,**kwargs): return get_swagger_ui_html( *args,**kwargs, swagger_js_url='https://cdn.bootcdn.net/ajax/libs/swagger-ui/4.10.3/swagger-ui-bundle.js', swagger_css_url='https://cdn.bootcdn.net/ajax/libs/swagger-ui/4.10.3/swagger-ui.css' ) applications.get_swagger_ui_html = swagger_monkey_patch @app.get('/') async def index(): return {"code": "hello world"} @app.get("/hello/{name}") async def say_hello(name:str): return {"message": "Hello, {}".format(name)} if __name__ == "__main__": uvicorn.run( app, host="0.0.0.0", port=8000 )
4、html模板渲染
pip install jinja2
安装后编写一个实例,文件目录如下:
├── templates
│ ├── index.html
├── main.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import uvicorn from fastapi import FastAPI,Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse("index.html", {"request": request, "name": "World"}) if __name__ == "__main__": uvicorn.run( app, host="0.0.0.0", port=8000 )
5、html发起GET请求:
文件目录如下:
├── templates
│ ├── get.html
├── main.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import uvicorn from fastapi import FastAPI,Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse("get.html", {"request": request, "name": "World"}) @app.get("/items/{item_id}") async def read_item2(item_id: int, q: str = None): return {"item_id": item_id, "q": q} if __name__ == "__main__": uvicorn.run( app, host="0.0.0.0", port=8000 )
get.html文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <title>GET请求</title> </head> <body> <button>GET</button> <div id="response"></div> </body> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $.ajax({ url: "/items/123456", type: "GET", data: { // GET参数键值对 q: "test" }, success: function(response){ console.log(response); // 在页面上显示响应结果 $("#response").html(JSON.stringify(response)); }, error: function(xhr, status, error){ console.log(xhr.responseText); // 在页面上显示错误信息 $("#response").html("Error: " + xhr.responseText); } }); }); }); </script> </html>
6、html发起POST请求:
├── templates
│ ├── post.html
├── main.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import uvicorn from fastapi import FastAPI,Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse("post.html", {"request": request, "name": "World"}) @app.post("/items/") async def create_item(request: Request): item = await request.json() return item if __name__ == "__main__": uvicorn.run( app, host="0.0.0.0", port=8000 )
post.html文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <title>POST请求</title> </head> <body> <button>POST</button> <div id="response"></div> </body> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $.ajax({ url: "/items/", type: "POST", contentType: "application/json", data: JSON.stringify({ "name": "example item", "price": "123456", }), success: function(response){ console.log(response); // 在页面上显示响应结果 $("#response").html(JSON.stringify(response)); }, error: function(xhr, status, error){ console.log(xhr.responseText); // 在页面上显示错误信息 $("#response").html("Error: " + xhr.responseText); } }); }); }); </script> </html>
做人一定要靠自己