FastAPI 學習之路(四十二)定制返回Response


     我們想要在接口中返回xml格式的內容,我們應該如何實現呢。

from fastapi import FastAPI,Response
@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")
if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

  那么我們請求下看下接口的實際返回。

 

 

        那么我們看下返回類型是xml格式的。

        在返回的時候,有時候我們需要在返回的headers。我們應該如何實現呢

@app.get("/legacy/")
def get_legacy_data():
    headers = {"X-Cat": "leizi", "Content-Language": "en-US"}
    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",
                    headers=headers)

其實很簡單。我們可以請求下

 

 

 

 

對應的接口可以正常返回,對應的Headers返回正常。

    要想設置cookie也很簡單

@app.get("/legacy/")
def get_legacy_data(response: Response):
    headers = {"X-Cat": "leizi", "Content-Language": "en-US"}
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>r
    </shampoo>
    """
    response.set_cookie(key="message", value="hello",path='/legacy/') 

  return Response(content=data, media_type="application/xml", headers=headers)

 我們看下結果

 

 

 

  接口可以正常返回我們設置的cookie,headers也可以正常返回。

文章首發在公眾號,歡迎關注。


免責聲明!

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



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