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

相关推荐
狗凯之家源码网30 分钟前
iOS C2 V2 与 Python FastAPI 全链路远控系统深度评测
python·ios·fastapi
触底反弹14 小时前
🚀 FastAPI 五大重难点深度剖析:从 500 报错到彻底搞懂 Depends、Pydantic 与 SQLAlchemy
python·fastapi
奔跑的熊猫1 天前
VSCode + FastAPI +AI Agent+langchain第一个程序
langchain·fastapi
全栈陈序员1 天前
【Python】基础语法入门(三十一)—— API 开发:用 FastAPI 构建 RESTful 接口
python·restful·fastapi
一枕槐安4872 天前
应届生 RAG 项目包装:FastAPI 检索服务接口设计指南
fastapi·web服务·rag·pydantic·接口封装
又蓝3 天前
【元宝搜索开发者征文大赛】用 FastAPI + Vue3 做了个 AI 炒股工具,接了六个分析师和腾讯元宝搜索
人工智能·python·ai·fastapi
外收内放3 天前
FastAPI猜字谜实战(8):收官
开发语言·python·学习·fastapi
hhb_6184 天前
FastAPI接口开发与性能优化实战
性能优化·fastapi
程序猿乐锅4 天前
【从0-1学习Python | 第九篇】继承
开发语言·后端·python·学习·fastapi
外收内放5 天前
FastAPI猜字谜实战(4):让AI主持人开口
开发语言·python·学习·fastapi