FastAPI(48)- 自定義響應之 HTMLResponse、PlainTextResponse
阿新 • • 發佈:2021-10-03
背景
- 上一篇文章講了通過 Response 自定義響應,但有一個缺點
- 如果直接返回一個 Response,資料不會自動轉換,也不會顯示在文件中
- 這一節開始講自定義響應
會講解多個響應型別
- HTMLResponse
- PlainTextResponse
- JSONResponse
- ORJSONResponse
- UJSONResponse
- RedirectResponse
- StreamingResponse
所有響應類都是繼承於 Response
HTMLResponse
作用
返回一些 HTML 程式碼
實際程式碼
from fastapi import FastAPI from fastapi.responses importHTMLResponse app = FastAPI() @app.get("/items/", response_class=HTMLResponse) async def read_items(): return """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html>"""
上面的栗子中,Response Header 的 Content-type 將為 text/html,並且會記錄在 OpenAPI 中
檢視 Swagger API 文件的 Response Header
請求結果
原始碼
只是聲明瞭下 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 = """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """ # 直接返回 HTMLResponse return HTMLResponse(content=html_content, status_code=200)
- 這樣的寫法效果是等價於上一個栗子的寫法
- 但這樣寫有個缺點,開頭也說了直接返回 Response 的缺點
- 不會記錄在 OpenAPI 中,比如不會記錄 Content-type,並且不會在 Swagger API 文件中顯示
檢視 Swagger API 文件的 Response Header
請求結果
新增 response_class 和 return Response 綜合使用
上面的栗子講了直接 return Response 的缺點,那麼可以結合使用 response_class 來避開問題
# 1、宣告 response_class @app.get("/items2/", response_class=HTMLResponse) async def read_items(): html_content = """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """ # 2、仍然 return HTMLResponse return HTMLResponse(content=html_content, status_code=200)
PlainTextResponse
作用
返回一些純文字資料
實際程式碼
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
預設是 application/json,現在改成了 text/plain
請求結果
原始碼
只是聲明瞭下 media_type,其他都沒變
假如直接 return 字串,Content-type 預設會是什麼型別?
from fastapi import FastAPI app = FastAPI() @app.get("/") async def main(): return "Hello World"
預設還是 application/json,因為 FastAPI 是使用 JSONResponse 返回響應的