fastAPI(1)--安装、路径参数、查询参数、请求body

一、依赖项
Python 3.6+

二、安装
pip install fastapi
需要一个ASGI服务器
pip install uvicorn


三、示例
新建文件main.py

#!/usr/bin/env python
# encoding: utf-8

from fastapi import FastAPI
import uvicorn
app = FastAPI()

@app.get('/')
async def main():
    return {"message": 'HelloWorld, FastAPI'}

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

运行http://127.0.0.1:8000

4.交互式API文档
访问以下两个地址,可获取自动生成的交互式API文档,并且当代码改动时文档会自动更新。方便我们的开发调试。
1、http://127.0.0.1:8000/docs (基于 Swagger UI)
2、http://127.0.0.1:8000/redoc (基于 ReDoc)

5.路径参数

@app.get('/items/{item_id}')
async def read_item(item_id):
    return {"item_id": item_id}

声明类型

@app.get("/items_type/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

这里,item_id被声明为int类型。

当使用字符串作为路径参数时如下:

因此借助类型声明,FastAPI给了你自动进行数据校验的能力。返回结果里清晰的指出了具体错误内容,这非常有利于你的代码开发和调试。

所有的数据校验能力都是在Pydantic的底层支持下得以实现的。你可以利用通用的数据类型如str、float、bool或者其他更复杂的数据类型进行类型注释。

6. 路径顺序问题

在有些情况下,路径声明的顺序不同会影响访问结果,这里应该留意下

#!/usr/bin/env python
# encoding: utf-8

from fastapi import FastAPI
import uvicorn
app = FastAPI()

@app.get('/me/xx')
async def read_item():
    return {"me": 'xx'}

@app.get("/me/{item_id}")
async def read_item(item_id: str):
    return {"item_id": item_id}

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

这里路径 /me/xx 应该在路径 /me/{item_id} 之前进行声明。否则,针对路径 /me/xx 的访问就会被匹配到 /me/{item_id},因为"xx"会被认为是路径参数 item_id 的值。

7. 使用枚举类型

使用Python Enum来声明路径参数的预定义值。

from enum import Enum

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

们声明了一个类ModelName,它继承自str(这样限制了值的类型必须是字符串类型)和Enum。

这里也给出了ModelName类属性的值。

使用示例如下:

#!/usr/bin/env python
# encoding: utf-8

from fastapi import FastAPI
import uvicorn
from enum import Enum

app = FastAPI()

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    if model_name == ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW!"}

    if model_name.value == "lenet":
        return {"model_name": model_name, "message": "LeCNN all the images"}

    return {"model_name": model_name, "message": "Have some residuals"}

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

这时路径参数model_name的类型是我们定义的枚举类ModelName。

我们可以访问可交互式文档 http://127.0.0.1:8000/docs 来快速进行接口验证。

8.路径参数中包含文件路径

比方说,你有一个路径操作与路径/files/{file_path}

但是您需要file_path自己包含一条路径,例如home/johndoe/myfile.txt

因此,该文件的URL类似于:/files/home/johndoe/myfile.txt

/files/{file_path:path}

在这种情况下,参数的名称为file_path,最后一部分:path告诉它参数应与任何路径匹配。

因此,可以将其用于:

from fastapi import FastAPI

app = FastAPI()


@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

可能需要包含的参数/home/johndoe/myfile.txt,并带有一个斜杠(/)。

在这种情况下,URL将为:/files//home/johndoe/myfile.txt,并且//files和之间使用双斜杠()home

9.查询参数

声明不属于路径参数的其他功能参数时,它们将自动解释为“查询”参数。

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

查询是?URL中位于后面的键值对的集合,以&字符分隔。

例如,在URL中:

http://127.0.0.1:8000/items/?skip=0&limit=10

...查询参数为:

skip=0 limit=10

在这个例子中,skip和limit都是有缺省值的。因此,下面URL的请求是等同的:

http://127.0.0.1:8000/items/
等同于
http://127.0.0.1:8000/items/?skip=0&limit=10
但如果你访问:
http://127.0.0.1:8000/items/?skip=20
那么实际的请求参数就是
skip=20 limit=10

10.可选参数

同样,可以通过将可选查询参数的默认值设置为来声明可选查询参数None

from typing import Optional
from fastapi import FastAPI
app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

在这种情况下,function参数q将是可选的,并且None默认情况下为默认值。item_id为 必填参数

11. 多个路径和查询参数

同时声明多个路径参数、多个请求参数,并且不用考虑声明顺序。FastAPI可以准确无误的识别参数类型。

@app.get('/users/{user_id}/items/{item_id}')
async def user_item(user_id: int, item_id: str, q: Optional[str] = None, short: bool = False):
    item = {'item_id': item_id, 'user_id': user_id}
    if q:
        item.update({'q': q})
    if not short:
        item.update({'desc': 'true'})
    return item

12.请求body--单个Request Body

创建数据模型,将数据模型声明为继承自的类BaseModel

from pydantic import BaseModel
class Item(BaseModel):
    name: str
    desc: Optional[str] = None
    price: float
    tax: Optional[float] = None

参数声明: 该模型声明一个JSON“ object”(或Python dict),在函数内部,您可以直接访问模型对象的所有属性

#!/usr/bin/env python
# encoding: utf-8

from fastapi import FastAPI
from typing import Optional
from pydantic import BaseModel

import uvicorn

class Item(BaseModel):
    name: str
    desc: Optional[str] = None
    price: float
    tax: Optional[float] = None

app = FastAPI()

@app.post('/items/')
async def create_item(item: Item):
    item_dict = item.dict()
    price_with_tax = item.price + item.tax
    item_dict.update({'price_with_tax': price_with_tax})
    return item_dict


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

运行后:

13. 同时使用Request Body参数、路径参数、请求参数

@app.put('/items/{item_id}')
async def create_item2(item_id: int, item: Item, q: Optional[str] = None):
    result = {'item_id': item_id, **item.dict()}
    if q:
        result.update({'q': q})
    return result
功能参数将被识别如下:
如果在path中也声明了该参数,它将用作路径参数。
如果参数是一个的单一类型(如int,float,str,bool,等等)将被解释为一个查询参数。
如果参数声明为Pydantic模型的类型,则它将被解释为请求body。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值