python3的uvicorn模块
FastAPI和uvicorn 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。
1、基本操作举例1:

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的运行参数中配置。

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

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

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

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文件:

<!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

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文件:

<!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>
做人一定要靠自己
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!