FastAPI 学习之路(四十一)定制返回Response

接口中返回xml格式内容

from fastapi import FastAPI, Response

app = FastAPI()


# ① xml
@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")

我们看下实际返回:

返回的类型是xml格式的,说明返回成功。

接口返回中定制headers

@app.get("/legacy_with_headers")
def get_legacy_with_headers_data():
    headers = {"X-Xtoken": "LC", "Content-Language": "en-US"}
    data = """<?xml version="1.0"?>
        <shampoo>
        <Header>
            Apply shampoo here.
        </Header>
        <Body>
            You'll have to use soap here.
            HERE SOMETHING HEADER YOU DEFINED
        </Body>
        </shampoo>
        """
    return Response(content=data, media_type="application/xml", headers=headers)

我们看下实际返回

对应的接口可以正常返回,对应的Headers返回正常。

设置cookie

@app.get("/legacy_with_header_cookie")
def legacy_with_header_cookie():
    headers = {"X-Xtoken": "LC-1", "Content-Language": "en-US"}
    data = """<?xml version="1.0"?>
            <shampoo>
            <Header>
                Apply shampoo here.
            </Header>
            <Body>
                You'll have to use soap here.
                HERE SOMETHING HEADER YOU DEFINED AND COOKIE
            </Body>
            </shampoo>
            """
    response = Response(content=data, media_type="application/xml", headers=headers)
    response.set_cookie(key="cookie_key_lc", value="mrli")
    return response

我们看下实际返回

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

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 08:40:02       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 08:40:02       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 08:40:02       57 阅读
  4. Python语言-面向对象

    2024-07-12 08:40:02       68 阅读

热门阅读

  1. C-MAPSS数据集-RUL剩余寿命预测

    2024-07-12 08:40:02       22 阅读
  2. Linux workqueue介绍

    2024-07-12 08:40:02       19 阅读
  3. C++异常处理throw try catch

    2024-07-12 08:40:02       23 阅读
  4. LiteOS系统的软件定时器

    2024-07-12 08:40:02       22 阅读
  5. Codeforces Round #956 (Div. 2) and ByteRace 2024

    2024-07-12 08:40:02       27 阅读
  6. C++学习笔记

    2024-07-12 08:40:02       27 阅读
  7. 调整视频帧率、分辨率

    2024-07-12 08:40:02       29 阅读
  8. 路由器内部优先级和外部优先级的区别

    2024-07-12 08:40:02       27 阅读
  9. 嵌入式驱动程序100道面试题(6万字长文)

    2024-07-12 08:40:02       23 阅读
  10. Linux中防火墙firewalld

    2024-07-12 08:40:02       24 阅读
  11. 针对不支持AJAX异步查询的虚拟空间做跨站点查询

    2024-07-12 08:40:02       28 阅读