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

相关推荐
掘金-我是哪吒21 小时前
分布式微服务系统架构第144集:FastAPI全栈开发教育系统
分布式·微服务·架构·系统架构·fastapi
jingyucsdn7 天前
AsyncIOScheduler与BackgroundScheduler的线程模型对比
fastapi
jingyucsdn8 天前
FastAPI集成APsecheduler的BackgroundScheduler+mongodb(精简)
fastapi
几道之旅8 天前
前端antd,后端fastapi,解决文件上传
前端·fastapi
Hello_WOAIAI9 天前
python中使用高并发分布式队列库celery的那些坑
python·fastapi
ZHOU_WUYI10 天前
FastAPI在 Nginx 和 Docker 环境中的部署
nginx·docker·fastapi
王学政211 天前
FastAPI 中间件
fastapi
小迅先生13 天前
AI开发 | Web API框架选型-FastAPI
开发语言·python·fastapi
老大白菜15 天前
双均线量化交易策略指南
python·fastapi
Msshu12316 天前
消费类,小家电产品如何做Type-C PD快充快速充电
python·单片机·嵌入式硬件·物联网·beautifulsoup·fastapi·tornado