FastAPI 教程(二)

路径参数(Path Parameter)

路径参数在路由里面用大括号括起来,在方法中需要把参数写出来,还可以标注参数的类型,例如:

from fastapi import FastAPI

app = FastAPI()

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

声明类型后,如果返回的结果不对,则会返回一个出错的 message。所有的校验都是通过 Pydantic 模块来实现的。

在路由文件中,定义在前面的路径会优先匹配。

使用枚举类型来做路径参数

我们可以使用 Python 的枚举类型 enum 来定义路径参数,限定其取值,例如:

from enum import Enum
from fastapi import FastAPI

class Name(str, Enum):
    Allan = '张三'
    Jon   = '李四'
    Bob   = '王五'

app = FastAPI()


@app.get("/{who}")
async def get_day(who: Name):
    if who == Name.Allan:
        return {"who": who, "message": "张三是德国人"}
    if who.value == '李四':
        return {"who": who, "message": "李四是英国人"}
    return {"who": who, "message": "王五是法国人"}

此时如果访问 http://localhost:8000/张三 ,就可以得到 {"who": 张三, "message": 张三是德国人} 。

包含路径的参数

在路径参数上把参数的类型设为 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 之类的路径。

查询参数(Query Parameter)

查询的参数如果是针对 get 请求,就是 url 后面用问号带起的参数,这些参数我们可以写在路由方法的参数中,例如:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    # ……

我们可以访问诸如 http://localhost/items/?skip=0&limit=10 来测试。

可选参数(Optional Parameters)

要使用可选参数,需要先导入 typing 模块中的 Optional,然后使用 Optional 并指定参数的默认值为 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}

如果不定义参数的值,则该参数为 必填参数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容