美文网首页
FastAPI 教程(二)

FastAPI 教程(二)

作者: Frederich | 来源:发表于2020-07-07 12:42 被阅读0次

    路径参数(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}
    

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

    相关文章

      网友评论

          本文标题:FastAPI 教程(二)

          本文链接:https://www.haomeiwen.com/subject/yysaqktx.html