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

相关推荐
梦因you而美5 小时前
LangChain-ReAct-Agent 智能客服系统 · 项目技术文档
langchain·agent·fastapi·扫地机器人·langgraph·rag 检索增强·react 智能客服
jsjzsl28 小时前
独立自由度框架下位置自由度的本体论特征、物理现象与新技术路径
python·flask·fastapi
嘻哈baby10 小时前
FastAPI + SQLite 从 0 写一个真正能用的待办 API
数据库·sqlite·fastapi
陈驰_050410 小时前
需求列表接口 422 Unprocessable Entity 排查与修复全记录
状态模式·fastapi·vue 3
Json____10 小时前
基于 FastAPI + Vue3 的在线拍卖系统技术解析
spring boot·后端·fastapi·wwwoop.com
创新技术阁10 小时前
FastapiAdmin 实战:二次开发前的准备(环境配置与项目启动)
前端·后端·fastapi
神秘的猪头1 天前
新版 LangChain Agent 核心架构:State、Context、ToolRuntime 与 Middleware
langchain·llm·fastapi
神秘的猪头1 天前
新版 LangChain Agent 入门:从 `bind_tools + while` 到 `create_agent`
langchain·fastapi
神秘的猪头1 天前
把新版 LangChain Agent 做成真正应用:Memory、Streaming、SSE 与 Structured Output
langchain·fastapi
minhuan1 天前
搭建本地人脸识别系统:解析FastAPI+InsightFace+FAISS全栈实现原理与优化方案26.6
fastapi·faiss·insightface·大模型应用·人脸识别模型·本地化人脸识别系统