• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
秋天的童话
梦想从此启航
博客园    首页    新随笔    联系   管理    订阅  订阅

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)
View Code

  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)
View Code

 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
        )
View Code

 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
        )
View Code

 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
        )
View Code

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>
View Code

 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
        )
View Code

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>
View Code

 

 
做人一定要靠自己
posted @ 2023-09-20 16:42  凯-子  阅读(1039)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3