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

   2024-10-19 6740
核心提示:在FastAPI中,可以使用response_model参数来指定不同的内容类型。例如,可以使用response_model参数来指定返回JSON格式的数据:f

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

from fastapi import FastAPIfrom pydantic import BaseModelapp = 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 FastAPIfrom fastapi.responses import HTMLResponseapp = FastAPI()@app.get("/", response_class=HTMLResponse)async def read_root():    return "<h1>Hello, World!</h1>"

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

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号