溫馨提示×

FastAPI中怎么處理不同的內(nèi)容類型

小億
98
2024-05-10 16:35:53
欄目: 編程語言

在FastAPI中,可以使用response_model參數(shù)來指定不同的內(nèi)容類型。例如,可以使用response_model參數(shù)來指定返回JSON格式的數(shù)據(jù):

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指定了返回的數(shù)據(jù)格式為Item類,這樣FastAPI會自動將返回的數(shù)據(jù)轉(zhuǎn)換為JSON格式。

如果要指定其他的內(nèi)容類型,可以使用response_class參數(shù)來指定。例如,可以使用response_class=HTMLResponse來返回HTML格式的數(shù)據(jù):

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指定了返回的數(shù)據(jù)格式為HTML格式。FastAPI會自動將返回的數(shù)據(jù)轉(zhuǎn)換為HTML格式。

0