FastAPI Response(三) 定制化的Response


作者:麥克煎蛋   出處:https://www.cnblogs.com/mazhiyong/ 轉載請保留這段聲明,謝謝!

 

默認情況下,FastAPI會基於JSONResponse來返回Response。

如果我們直接返回Response,數據格式不會被自動轉換,並且交互式文檔也不會自動生成。

下面是一些常用的Response類型。

Response

Response主類,所有其他的Response都繼承自這個類。

它接收以下參數信息:

  • content - str 或者 bytes.
  • status_code - HTTP 狀態碼.
  • headers - 字符串字典.
  • media_type - media type. 例如"text/html".

FastAPI會自動包含Content-Length,以及Content-Type,charset等頭信息。

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/legacy/")
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return Response(content=data, media_type="application/xml")

 

我們可以在路徑操作裝飾器中聲明要返回的具體Response類型,返回的內容會被放入到指定的Response

並且如果我們指定的Response支持JSON media類型,例如JSONResponse或者UJSONResponse,那么返回的數據就會被自動轉換成Pydantic模型(通過response_model指定)。

HTMLResponse

接收文本或者字節內容,返回HTML reponse。

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

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>
    """

PlainTextResponse

接收文本或者字節內容,返回純文本 reponse。

from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()


@app.get("/", response_class=PlainTextResponse)
async def main():
    return "Hello World"

JSONResponse

返回application/json格式的response。FastAPI默認返回的response。

RedirectResponse

返回HTTP重定向。默認狀態碼為307(臨時重定向)。

from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()


@app.get("/typer")
async def read_typer():
    return RedirectResponse("https://typer.tiangolo.com")

StreamingResponse

接收一個異步的發生器或者普通的發生器/枚舉器,對返回結果流式輸出。

from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()


async def fake_video_streamer():
    for i in range(10):
        yield b"some fake video bytes"


@app.get("/")
async def main():
    return StreamingResponse(fake_video_streamer())

如果我們有一個file-like對象(比如用open()打開),我們就可以用StreamingResponse來返回該對象。

from fastapi import FastAPI
from fastapi.responses import StreamingResponse

some_file_path = "large-video-file.mp4"
app = FastAPI()


@app.get("/")
def main():
    file_like = open(some_file_path, mode="rb"return StreamingResponse(file_like, media_type="video/mp4")

FileResponse

異步流式輸出一個文件。

不同於其他response的初始化參數信息:

  • path - 文件路徑
  • headers - 定制頭信息,字典格式
  • media_type - media type,如果沒有設置則會根據文件名或文件路徑來推斷media type
  • filename - 文件名。如果設置,會被包含到response的Content-Disposition中

文件response會包含合適的Content-Length, Last-Modified 以及 ETag 頭信息內容。

from fastapi import FastAPI
from fastapi.responses import FileResponse

some_file_path = "large-video-file.mp4"
app = FastAPI()


@app.get("/")
async def main():
    return FileResponse(some_file_path)

 

缺省response類

我們可以指定缺省response類,如下我們指定了ORJSONResponse為缺省使用的response類。

from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI(default_response_class=ORJSONResponse)


@app.get("/items/")
async def read_items():
    return [{"item_id": "Foo"}]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM