FastAPI Response(二) 直接返回Response對象


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

 

在FastAPI路徑操作中,我們通常直接返回以下數據類型:dict,list,Pydantic模型,數據庫模型以及其他數據類型。

FastAPI通過jsonable_encoder函數自動把返回數據轉換為JSON格式,然后把JSON兼容的數據內容傳送給JSONResponse對象並返回給終端用戶。

在有些情況下,我們需要在路徑操作中直接返回Response對象,這樣我們能有更多的操作靈活性,比如自定義頭信息、自定義Cookie信息等。

 

返回Response

我們可以直接返回Response或者它的任何子類。 JSONResponse實際上也是Response的子類。

這個時候FastAPI不會做任何數據轉換和數據校驗,而是直接返回數據。

我們具有很大的靈活性,可以返回任何數據類型,重寫數據聲明或者數據校驗。

 

我們可以利用jsonable_encoder把數據轉換成JSON兼容格式。

from datetime import datetime
from typing import Optional

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: Optional[str] = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
json_compatible_item_data = jsonable_encoder(item) return JSONResponse(content=json_compatible_item_data)

返回自定義Response

我們來看一下如何返回一個自定義的Response,比如返回XML格式的數據。

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

 


免責聲明!

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



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