在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格式。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1024033.html