FastAPI(48)- 自定义响应之 HTMLResponse、PlainTextResponse
FastAPI(48)- 自定义响应之 HTMLResponse、PlainTextResponse
- 上一篇文章讲了通过 Response 自定义响应,但有一个缺点
- 如果直接返回一个 Response,数据不会自动转换,也不会显示在文档中
- 这一节开始讲自定义响应
会讲解多个响应类型
作用
作用
请求结果
只是声明了下 media_type,其他都没变
返回自定义 Response 的第二种方式
- 上面的两个栗子是通过在路径操作装饰器的 response_class 来声明 Response @app.get("/items/", response_class=HTMLResponse)
- 下面的栗子将会讲解在路径操作函数中直接 return Response
实际代码
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/items/")
async def read_items():
html_content = """
Some HTML in here
Look ma! HTML!
"""
# 直接返回 HTMLResponse
return HTMLResponse(content=html_content, status_code=200)
- 这样的写法效果是等价于上一个栗子的写法
- 但这样写有个缺点,开头也说了直接返回 Response 的缺点
- 不会记录在 OpenAPI 中,比如不会记录 Content-type,并且不会在 Swagger API 文档中显示
查看 Swagger API 文档的 Response Header
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/items/")
async def read_items():
html_content = """
Some HTML in here
Look ma! HTML!
"""
# 直接返回 HTMLResponse
return HTMLResponse(content=html_content, status_code=200)
- 这样的写法效果是等价于上一个栗子的写法
- 但这样写有个缺点,开头也说了直接返回 Response 的缺点
- 不会记录在 OpenAPI 中,比如不会记录 Content-type,并且不会在 Swagger API 文档中显示
查看 Swagger API 文档的 Response Header
添加 response_class 和 return Response 综合使用
# 1、声明 response_class
@app.get("/items2/", response_class=HTMLResponse)
async def read_items():
html_content = """
Some HTML in here
Look ma! HTML!
"""
# 2、仍然 return HTMLResponse
return HTMLResponse(content=html_content, status_code=200)
PlainTextResponse
Look ma! HTML!
""" # 2、仍然 return HTMLResponse return HTMLResponse(content=html_content, status_code=200)返回一些纯文本数据
实际代码
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
app = FastAPI()
@app.get("/", response_class=PlainTextResponse)
async def main():
return "Hello World"
查看 Swagger API 文档的 Response Header
源码
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def main():
return "Hello World"
默认还是 application/json,因为 FastAPI 是使用 JSONResponse 返回响应的
- 本文作者: 小菠萝测试笔记
- 本文链接: