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

相关推荐
逻极12 小时前
FastAPI项目结构实战:从混乱到清晰,我们如何提升团队开发效率300%
fastapi·架构设计·项目结构·代码组织
yaoty3 天前
FastAPI 流式响应中,如何优雅处理客户端断连后的数据库操作?
mysql·fastapi
百***49004 天前
开源模型应用落地-FastAPI-助力模型交互-进阶篇-中间件(四)
开源·交互·fastapi
逻极5 天前
FastAPI 从零开始:环境搭建与第一个API
fastapi
数据知道6 天前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目
码二哥6 天前
借助豆包将vllm推理deepseek-ocr改成web服务访问
ocr·fastapi·vllm·豆包·deepseek-ocr
一个java开发6 天前
FastAPI 源码阅读==浏览器一次请求到 uvicorn/FastAPI 的底层流程(含 epoll/FD)
fastapi
BestSongC7 天前
基于VUE和FastAPI的行人目标检测系统
vue.js·人工智能·yolo·目标检测·fastapi
数据知道7 天前
FastAPI项目:构建打字速度测试网站(MySQL版本)
数据库·python·mysql·fastapi·python项目
A尘埃9 天前
Python后端框架:FastAPI+Django+Flask
python·django·flask·fastapi