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

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

  • 相关阅读:
    Getting Started with MongoDB (MongoDB Shell Edition)
    Ioc
    BsonDocument
    Find or Query Data with C# Driver
    Insert Data with C# Driver
    Connect to MongoDB
    What's the difference between returning void and returning a Task?
    Import Example Dataset
    jQuery来源学习笔记:整体结构
    Word文件交换的电脑打开字体、排版变化的原因和解决方法!
  • 原文地址:https://www.cnblogs.com/leiziv5/p/15416839.html
Copyright © 2011-2022 走看看