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

相关推荐
onelafite1 天前
小红书笔记评论一键获取,实时查看作品数据
api·fastapi
shao9185162 天前
Gradio全解11——Streaming:流式传输的视频应用(2)——Twilio:网络服务提供商
fastapi·handler·stun·turn·ice·twillo
枫叶V2 天前
用 FastAPI 实现大文件分片上传与断点续传(含可运行示例与客户端脚本,仅供参考)
python·fastapi
蓝倾5 天前
利用API接口合规获取淘宝店铺所有商品实战案例(2025年最新版)
api·fastapi
肥肠可耐的西西公主6 天前
后端(fastAPI)学习笔记(CLASS 1):扩展基础
笔记·学习·fastapi
红鼻子时代7 天前
Day5-中间件与请求处理
中间件·fastapi·后端开发
蓝倾8 天前
京东商品属性API数据解析:颜色、尺寸与材质
api·fastapi
CodeDevMaster9 天前
使用Transformers、ChatGLM3项目、创建FastAPI应用等方式部署调用ChatGLM3-6B模型
llm·fastapi·chatglm (智谱)
我就是全世界11 天前
【2025终极对决】Python三大后端框架Django vs FastAPI vs Robyn,你的选择将决定项目生死?
python·django·fastapi
威风的虫13 天前
FastAPI 核心实战:精通路径参数、查询参数与数据交互
python·交互·fastapi