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

相关推荐
Just Jump1 天前
2个框架(Tornado/FastAPI)、3个模块(threading/ThreadPoolExecutor/asyncio)的高并发异步实现和对比理解
fastapi·tornado·异步高并发
Li emily2 天前
解决了加密货币api多币种订阅时的数据乱序问题
人工智能·python·api·fastapi
Muyuan19983 天前
31.Cursor 初体验:用 AI Agent 给 PaperPilot 做一次最小工程重构
人工智能·python·重构·django·fastapi·faiss
csdn小瓯3 天前
FastAPI 依赖注入与状态管理实战:构建高可维护的异步后端
fastapi
dinl_vin3 天前
FastAPI 系列(一)· 初体验——从 Spring Boot 工程师视角认识 FastAPI
后端·python·fastapi
海市公约3 天前
从 CRUD 到 AI 工程:基于 FastAPI + Dify 的 AI 面试模拟系统实践
prompt·fastapi·项目实战·dify·ai工作流·后端架构
码界筑梦坊3 天前
120-基于Python的食品营养特征数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·echarts·fastapi
Muyuan19984 天前
30.通过Claude code做项目系统测试
运维·服务器·人工智能·fastapi
Muyuan19984 天前
29.从 FAISS 到 Milvus:给我的 RAG Agent 项目加一层可替换的向量检索后端
fastapi·milvus·faiss
码界筑梦坊4 天前
123-基于Python的特斯拉超级充电站分布数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·echarts·fastapi