python之FastApi简单应用

1.Python环境与安装

python环境:Python 3.6+

安装FastApi:

pip install --index-url https://pypi.tuna.tsinghua.edu.cn/simple/ fastapi

2.简单应用

from fastapi import FastAPI
import uvicorn

# 创建 FastAPI 实例
app = FastAPI()

# 根路径
@app.get("/")
async def root():
    return {"message": "Hello World"}

# 带路径参数的 GET 请求
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

# 带查询参数的 GET 请求
@app.get("/users/")
async def read_user(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}


def main():
    uvicorn.run(app, host="0.0.0.0", port=8000)
    
# 确保当脚本直接运行时也能执行main函数
if __name__ == "__main__":
    main()

2.1 运行:

python -m main

这样我们就能在127.0.0.1:8000上运行上面的几个路由链接, uvicorn是用于生成端口服务

http://127.0.0.1:8000/

http://127.0.0.1:8000/items/2

http://127.0.0.1:8000/users

2.2 代码解析:

async def read_item(item_id: int):

定义一个异步函数read_item ,表示期望接收一个int型的数据

3.应用添加数据模型验证

from fastapi import FastAPI
from pydantic import BaseModel,ValidationError
from typing import Optional
import uvicorn

app = FastAPI()

# 定义数据模型
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


# POST 请求根目录
@app.post("/")
async def root(item: Item):
    item = item.dict()
    return item
# POST 请求创建项目
@app.post("/items/")
async def create_item(item: dict):
    try:
        #item = item.dict()
        if item.get('tax') is None: #用get即使不存在tax这个字段,也不会报错。类似php的isset
            return {"error":'tax is require'}
        if item['tax']:
            price_with_tax = item['price'] + item['tax']
            item.update({"price_with_tax": price_with_tax})
        return item
    except Exception  as e:
        print(item)
        return str(e)

# PUT 请求更新项目
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    return {"item_id": item_id, **item.dict()}

def main():
    uvicorn.run(app, host="0.0.0.0", port=8000)
    
# 确保当脚本直接运行时也能执行main函数
if __name__ == "__main__":
    main()

3.1 运行

同上

3.2 代码解析

class Item(BaseModel):

    name: str

    description: Optional[str] = None

    price: float

    tax: Optional[float] = None

定义一个数据模型,指定数据的类型

async def root(item: Item):
    item = item.dict() #转为字典
    return item

期望接收一个Item类的实例,存入时由于Item类继承BaseModel,会自动验证数据,如果数据不符合预期,会弹出下面这样的提示。比如我这里没有传price,而数据模型并不允许none:

{
    "detail": [
        {
            "type": "missing",
            "loc": [
                "body",
                "price"
            ],
            "msg": "Field required",
            "input": {
                "name": "1",
                "description": "1"
            }
        }
    ]
}

async def create_item(item: dict):

表示期望接收一个字典型型的数据 , 如果用api测试工具,一般body的传值方式为json

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿John

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值