zoukankan      html  css  js  c++  java
  • 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")
        return Response(content=data, media_type="application/xml",
                        headers=headers)

     我们看下结果

     

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

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

  • 相关阅读:
    游标
    mobaxterm安装与使用(root_35/37/36/121)
    美团笔试--修改矩阵
    美团笔试1--螺旋矩阵
    assert函数
    2019年头条笔试--围坐分糖果
    邻值查找——stl函数lower_bound和upper_bound的使用
    动态规划练习1--腾讯暑期实习正式批
    Windows 7下硬盘安装CentOS6.4的解决方法
    Sublime Text 3 的一些基本使用方法和配置
  • 原文地址:https://www.cnblogs.com/leiziv5/p/15416839.html
Copyright © 2011-2022 走看看