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

相关推荐
zizle_lin10 小时前
优雅使用Gunicorn进程管理FastAPI
服务器·fastapi·gunicorn
掘金-我是哪吒2 天前
分布式微服务系统架构第131集:fastapi-python
分布式·python·微服务·系统架构·fastapi
Anesthesia丶5 天前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
weixin_307779135 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
掘金-我是哪吒5 天前
分布式微服务系统架构第130集:Python工程化FastAPI,运维Nginx-keepalived+Nginx实现高可用集群
运维·分布式·微服务·系统架构·fastapi
LingRannn5 天前
JWT的介绍与在Fastapi框架中的应用
fastapi
Python私教5 天前
使用FastAPI和React以及MongoDB构建全栈Web应用05 FastAPI快速入门
前端·react.js·fastapi
Python私教6 天前
全栈开发实战:FastAPI + React + MongoDB 构建现代Web应用
前端·react.js·fastapi
weixin_307779136 天前
使用FastAPI和Apache Flink构建跨环境数据管道
redis·python·云计算·fastapi·aws
真智AI9 天前
构建安全的机器学习推理API:基于FastAPI的用户认证与管理实战
安全·机器学习·fastapi