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

相关推荐
钱彬 (Qian Bin)1 天前
项目实践17—全球证件智能识别系统(开发基于LabelMe标注的可视化审核接口)
qt·fastapi·全球证件识别
ghgxm5202 天前
Fastapi_00_学习策略与学习计划
python·学习·前端框架·npm·fastapi
我是菜鸟0713号3 天前
Qt + Python 算法集成的一种低耦合实践:FastAPI 服务化方案
python·qt·fastapi
a程序小傲3 天前
蚂蚁Java面试被问:向量数据库的相似度搜索和索引构建
开发语言·后端·python·架构·flask·fastapi
风送雨3 天前
FastAPI 学习教程 · 第6部分
学习·fastapi
风送雨3 天前
FastAPI 学习教程 · 第5部分
jvm·学习·fastapi
越甲八千3 天前
FastAPI传参类型
开发语言·python·fastapi
天若有情6733 天前
【Python】从0到1实现轻量级接口测试工具:基于Python+FastAPI+Pytest
python·测试工具·fastapi
测开小林3 天前
加入L-Tester开源项目:自动化测试平台
自动化测试·测试开发·开源·fastapi·测试平台