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

相关推荐
AI木马人4 小时前
1.人工智能实战:大模型推理接口响应慢?从模型加载到 FastAPI 部署的完整优化方案
人工智能·python·fastapi
.柒宇.7 小时前
FastAPI 基础指南:从入门到实战
开发语言·python·fastapi
迪菲赫尔曼9 小时前
从 0 到 1 打造工业级推理控制台:UltraConsole(Ultralytics + FastAPI + React)开源啦!
前端·yolo·react.js·计算机视觉·开源·fastapi
曲幽12 小时前
用了loguru我才明白,Python日志还能这么写
python·logging·fastapi·web·async·loguru·handler·uvicorn
.柒宇.13 小时前
FastAPI进阶教程
开发语言·python·fastapi
Mr.朱鹏1 天前
【Python 进阶 | 第四篇】Psycopg3 + Flask 实现 PostgreSQL CRUD 全流程:从连接池到RESTful接口
python·postgresql·flask·virtualenv·fastapi·pip·tornado
曲幽2 天前
FastAPI配置管理避坑指南:从硬编码到 .env 与 pydantic_settings 类,连路由用法都给你捋清楚
python·fastapi·web·settings·config·pydantic·.env·dotenv·.env.prod
世界尽头与你2 天前
FastAPI Swagger Api 接口未授权访问漏洞
安全·网络安全·渗透测试·fastapi
rannn_1113 天前
【FastAPI|快速入门】第一个FastAPI程序、路由、参数、相应类型、自定义响应数据格式、异常响应处理
python·ai·fastapi·web·开发
java1234_小锋3 天前
FastAPI + Vue 3 前后端分离:项目设计与工程实践(偏“能落地”的最佳实践)
前端·vue.js·fastapi