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

相关推荐
溪语流沙2 天前
【Web全栈进阶】FastAPI工程化:APIRouter拆分 + 配置 + 依赖注入
java·前端·fastapi
小园子的小菜2 天前
FastAPI 全方位入门实战:高性能 Python Web 框架开发指南
python·pycharm·fastapi
云和数据.ChenGuang2 天前
langchain4j InMemoryEmbeddingStore常用的方法
java·人工智能·windows·java-ee·fastapi·springai
爱写代码的倒霉蛋4 天前
FastAPI的接口实现流程讲解
fastapi
在世修行5 天前
干货:文件上传端点解析
python·fastapi·接收上传
云和数据.ChenGuang5 天前
JAVAEE AI工程师路线图
java·人工智能·java-ee·fastapi·springai·langchain4j
风早爽太5 天前
Python 学习笔记:SQLModel 使用外键关联查询数据
python·fastapi·sqlmodel
风早爽太6 天前
Python 学习笔记:数据库迁移工具 ‌Alembic
数据库·python·fastapi·alembic
Web3&Basketball6 天前
用FastAPI+Redis 复刻常驻Agent
redis·bootstrap·fastapi
风早爽太9 天前
Python 开发笔记:配置生产环境中 Celery Worker 的独立进程启动方式
python·fastapi