在应用中使用response的ContentType可以通过设置Content-Type头来指定响应的内容类型。下面是一些常见的ContentType的示例:
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="<h1>Hello, World!</h1>", media_type="text/html")
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,可以确保客户端正确解析和处理响应的内容。