fastapi(二十三)-高级用户指南

路径操作高级配置

OpenAPI的operationId
您可以使用operationId参数设置在路径操作中使用的OpenAPI operation_id。

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/", operation_id="some_specific_id_you_define")
async def read_items():
    return [{"item_id": "Foo"}]

使用路径操作功能名称作为operationId

from fastapi import FastAPI
from fastapi.routing import APIRoute

app = FastAPI()


@app.get("/items/")
async def read_items():
    return [{"item_id": "Foo"}]


def use_route_names_as_operation_ids(app: FastAPI) -> None:
    """
    Simplify operation IDs so that generated API clients have simpler function
    names.

    Should be called only after all routes have been added.
    """
    for route in app.routes:
        if isinstance(route, APIRoute):
            route.operation_id = route.name  # in this case, 'read_items'


use_route_names_as_operation_ids(app)

要将路径操作从生成的OpenAPI架构(以及自动文档系统)中排除,请使用参数include_in_schema并将其设置为False

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/", include_in_schema=False)
async def read_items():
    return [{"item_id": "Foo"}]

docstring的高级描述
您可以限制OpenAPI 的路径操作函数的文档字符串中使用的行。
添加一个\f(转义的“换页符”字符)会使FastAPI截断此时用于OpenAPI的输出。
它不会显示在文档中,但是其他工具(例如Sphinx)将可以使用其余的工具。

@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(*, item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    \f
    :param item: User input.
    """
    return item

自定义响应-HTML,流,文件等

默认情况下,FastAPI将使用来返回响应JSONResponse。

您可以通过Response直接返回a来覆盖它,如直接返回响应中所示。

但是,如果Response直接返回a ,则不会自动转换数据,也不会自动生成文档(例如,Content-Type作为生成的OpenAPI的一部分,在HTTP标头中包含特定的“媒体类型” )。

但是您也可以Response在path操作decorator中声明要使用的。

从路径操作函数返回的内容将放在其中Response。

并且,如果该对象Response具有JSON媒体类型(application/json),则与JSONResponseand一样UJSONResponse,返回的数据将使用response_model在path操作decorator中声明的任何Pydantic自动转换(并过滤)。
使用ORJSONResponse
例如,如果要压缩性能,则可以安装和使用orjson并将响应设置为ORJSONResponse。

from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI()


@app.get("/items/", response_class=ORJSONResponse)
async def read_items():
    return [{"item_id": "Foo"}]

HTML响应
要直接从FastAPI返回HTML响应,请使用HTMLResponse。

导入HTMLResponse。
传递HTMLResponse的参数content_type你的路径运行。

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.get("/items/", response_class=HTMLResponse)
async def read_items():
    return """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """

FileResponse
异步传输文件作为响应。
与其他响应类型相比,采用不同的参数集进行实例化:

  • path -要流式传输的文件的文件路径。
  • headers -包含的任何自定义标头(作为字典)。
  • media_type-提供媒体类型的字符串。如果未设置,则文件名或路径将用于推断媒体类型。
  • filename-如果设置,则将包含在响应中Content-Disposition。
from fastapi import FastAPI
from fastapi.responses import FileResponse

some_file_path = "large-video-file.mp4"
app = FastAPI()


@app.get("/")
async def main():
    return FileResponse(some_file_path)

响应cookie
使用Response参数
您可以Response在路径操作函数中声明类型的参数。

然后,您可以在该时间响应对象中设置cookie 。

from fastapi import FastAPI, Response

app = FastAPI()


@app.post("/cookie-and-object/")
def create_cookie(response: Response):
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return {"message": "Come to the dark side, we have cookies"}

Response直接返回
当Response直接在代码中返回时,您还可以创建cookie 。

为此,您可以按照直接返回响应中所述创建响应。

然后在其中设置Cookies,然后将其返回:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.post("/cookie/")
def create_cookie():
    content = {"message": "Come to the dark side, we have cookies"}
    response = JSONResponse(content=content)
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return response

响应标题
使用Response参数¶
您可以Response在路径操作函数中声明类型的参数(就像对cookie一样)。

然后,您可以在该时间响应对象中设置标题。

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/headers-and-object/")
def get_headers(response: Response):
    response.headers["X-Cat-Dog"] = "alone in the world"
    return {"message": "Hello World"}

Response直接返回
您还可以在Response直接返回时添加标头。

按照直接返回响应中所述创建响应,并将标头作为附加参数传递:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.get("/headers/")
def get_headers():
    content = {"message": "Hello World"}
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)

响应-更改状态码
使用Response参数

from fastapi import FastAPI, Response, status

app = FastAPI()

tasks = {"foo": "Listen to the Bar Fighters"}


@app.put("/get-or-create-task/{task_id}", status_code=200)
def get_or_create_task(task_id: str, response: Response):
    if task_id not in tasks:
        tasks[task_id] = "This didn't exist before"
        response.status_code = status.HTTP_201_CREATED
    return tasks[task_id]
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值