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 小时前
咖啡工坊 · FastAPI 22 章教程合集
服务器·人工智能·python·fastapi
深海鱼肝油ya21 小时前
基于FastAPI的AI智能体Web系统构建(二)
人工智能·fastapi·python开发·异步框架·agent开发
咕噜咕噜啦啦2 天前
FastAPI
fastapi
CaffeinePro4 天前
FastAPI高并发实战:缓存、分布式限流、链路日志三位一体架构
后端·fastapi
java1234_小锋4 天前
FastAPI python web开发- 集成SQLAlchemy ORM 操作数据库
fastapi
不瘦80斤不改名5 天前
全家桶、乐高积木与类型引擎:重新认识 Django、Flask 与 FastAPI
django·flask·fastapi
Exclusive_Cat6 天前
FastAPI热重载失效?降级uvicorn解决
python·fastapi
初学AI的小高7 天前
FastAPI 工程实践:LLM 应用的 API 设计之道
后端·fastapi
java1234_小锋7 天前
FastAPI python web开发- 中间件
fastapi
不能只会打代码7 天前
Day 002 — Python 工程化 & FastAPI & 数据库速通
数据库·redis·python·docker·fastapi·测试