在应用中使用response
的ContentType
可以通过设置Content-Type
头来指定响应的内容类型。下面是一些常见的ContentType
的示例:
- 对于返回HTML内容的响应,可以将
ContentType
设置为text/html
。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/html")
def read_html():
return Response(content="Hello, World!
", media_type="text/html")
- 对于返回JSON内容的响应,可以将
ContentType
设置为application/json
。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/json")
def read_json():
return {"message": "Hello, World!"}
- 对于返回文件的响应,可以将
ContentType
设置为相应文件的MIME类型。
from fastapi import FastAPI
from starlette.responses import FileResponse
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/file")
def read_file():
return FileResponse(path="path_to_file", media_type="application/pdf")
通过设置适当的ContentType
,可以确保客户端正确解析和处理响应的内容。