温馨提示×

FastAPI中怎么处理不同的内容类型

小亿
83
2024-05-10 16:35:53
栏目: 编程语言

在FastAPI中,可以使用response_model参数来指定不同的内容类型。例如,可以使用response_model参数来指定返回JSON格式的数据:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    return {"name": "Foo", "description": "This is a test item"}

在上面的例子中,response_model=Item指定了返回的数据格式为Item类,这样FastAPI会自动将返回的数据转换为JSON格式。

如果要指定其他的内容类型,可以使用response_class参数来指定。例如,可以使用response_class=HTMLResponse来返回HTML格式的数据:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def read_root():
    return "<h1>Hello, World!</h1>"

在上面的例子中,response_class=HTMLResponse指定了返回的数据格式为HTML格式。FastAPI会自动将返回的数据转换为HTML格式。

0