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

相关推荐
onelafite4 天前
一键式商品信息获取:京东API返回值深度挖掘
api·fastapi
苏侠客8524 天前
在docker上部署fastapi的相关操作
docker·容器·fastapi
令狐寻欢6 天前
AI 大模型应用进阶系列(五):FastAPI 入门
人工智能·python·fastapi
六毛的毛10 天前
FastAPI入门:中间件、CORS跨域资源共享、SQL数据库
数据库·中间件·fastapi
蓝倾10 天前
批量获取亚马逊商品SKU商品规格调用流程
api·fastapi
蓝倾13 天前
京东商品销量数据如何获取?API接口调用操作详解
前端·api·fastapi
蓝倾17 天前
小红书获取笔记详情API接口调用操作指南
前端·api·fastapi
六毛的毛17 天前
FastAPI入门:表单数据、表单模型、请求文件、请求表单与文件
前端·python·fastapi
码@农18 天前
Python三大Web框架:FastAPI vs Flask vs Django 详解与快速入门指南
python·fastapi
MC皮蛋侠客18 天前
AsyncIOScheduler 使用指南:高效异步任务调度解决方案
网络·python·fastapi