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

相关推荐
放下华子我只抽RuiKe52 小时前
FastAPI 全栈后端(四):认证与授权
开发语言·前端·javascript·python·深度学习·react.js·fastapi
放下华子我只抽RuiKe57 小时前
FastAPI 全栈后端(六):中间件与依赖注入
ai·中间件·fastapi·ai编程·qwen·ai大模型·openclaw
li星野9 小时前
Refresh Token 实战:让用户“无感”续期,告别重复登录
fastapi
放下华子我只抽RuiKe511 小时前
FastAPI 全栈后端(五):后台任务与消息队列
前端·javascript·react.js·ai·前端框架·fastapi·ai编程
li星野1 天前
从零构建安全文件上传系统:FastAPI + JWT + 密码哈希 + Streamlit 前端 + SQLite
安全·哈希算法·fastapi
郭庆汝2 天前
FastAPI使用笔记
笔记·fastapi
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(二):路由与数据模型
前端·人工智能·react.js·前端框架·html·fastapi
XGeFei2 天前
【Fastapi学习笔记(7)】—— Fastapi 中间件、前端跨域请求
笔记·学习·fastapi
li星野2 天前
构建安全的文件上传系统:FastAPI + JWT 认证 + Streamlit 前端 + SQLite 数据库
数据库·安全·fastapi
动能小子ohhh3 天前
DocForge平台的设计与开发--文件上传接口的实现
开发语言·人工智能·python·langchain·ocr·fastapi