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也可以正常返回。

文章首发在公众号,欢迎关注。

posted @   北漂的雷子  阅读(1527)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示