python系列28:fastapi部署应用

1. 介绍与安装

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,类似flask,Django,webpy
在部署时可能需要用到下面的库:

Uvicorn 或者 Hypercorn负责ASGI 服务器。
Starlette 负责 web 部分。
Pydantic 负责数据部分。

都用pip install安装即可

2. 基础

示例代码如下:

## main.py
from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str):
    return {"item_id": item_id, "q": q}

如果你的代码里会出现 async / await,请使用 async def。
通过以下命令运行服务器:

uvicorn main:app --reload

或者在python里面执行:

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app="main:app", host="127.0.0.1", port=8000)

现在访问 http://127.0.0.1:8000/docs。你会看到自动生成的交互式 API 文档(由 Swagger UI生成):
python系列28:fastapi部署应用_第1张图片

3. Pydantic:标准Python类型提升性能

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}

使用Pydantic后的好处包括:

  1. 文档中parameters更详细了
  2. 可以直接在文档中输入样例,然后点击Try it out进行交互
  3. 会检查输入格式

你可能感兴趣的:(python系列,python,fastapi,开发语言)