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

相关推荐
中年程序员一枚9 小时前
python开发接口uvicorn方法启动FastAPI,postman调用接口
python·postman·fastapi
周杰伦_Jay16 小时前
【FastAPI】核心特性、目录结构与生产级实践
架构·开源·fastapi
懒人村杂货铺2 天前
FastAPI + 前端(Vue/React)Docker 部署全流程
前端·vue.js·fastapi
创新技术阁2 天前
CryptoAiAdmin 项目后端启动过程详解
后端·python·fastapi
lomocode3 天前
接口报 500 了,日志里却空空的?FastAPI 异常处理最佳实践
fastapi·ai编程
百分三十七3 天前
FastApi接口文档访问超时加载不出来解决方案来了
python·fastapi
计算衎3 天前
基于python的FastAPI框架目录结构介绍、开发思路和标准开发模板总结
开发语言·python·fastapi
闲人编程3 天前
FastAPI路径操作、查询参数与请求体:构建高效API的完整指南
python·api·fastapi·请求体·codecapsule·查询参数
Misnice4 天前
使用 SQLAlchemy 连接数据库
数据库·python·mysql·fastapi
计算衎4 天前
FastAPI+ PostgreSQL+ VUE 实现一个数据平台展示案例
vue.js·python·postgresql·fastapi