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

相关推荐
像风一样自由20201 天前
FastMCP与FastAPI:构建自定义MCP服务器
服务器·microsoft·fastapi
数据智能老司机2 天前
使用 FastAPI 构建生成式 AI 服务——与生成模型的实时通信
llm·openai·fastapi
数据智能老司机2 天前
使用 FastAPI 构建生成式 AI 服务——AI集成与模型服务
llm·openai·fastapi
十分钟空间2 天前
有哪些常用的Python后端开发框架?
python·flask·fastapi
老大白菜3 天前
FastAPI WebSocket 聊天应用详细教程
websocket·网络协议·fastapi
众智创新团队6 天前
Flutter与FastAPI的OSS系统实现
flutter·fastapi·oss
Light608 天前
Python依赖注入完全指南:高效解耦、技术深析与实践落地
python·设计模式·单元测试·fastapi·依赖注入·解耦
SpikeKing8 天前
Server - 使用 FastAPI + OpenTelemetry + Zipkin 搭建 Python 服务
python·api·fastapi·zipkin·opentelemetry
趣谈AI10 天前
使用Trae编辑器开发Python Api (FastApi 框架)
python·编辑器·fastapi
Amd79413 天前
FastAPI依赖注入性能优化策略
单例模式·性能优化·fastapi·依赖注入·错误处理·异步编程·缓存机制