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

相关推荐
小宁爱Python32 分钟前
FastAPI+Sqlite+HTML的登录注册与文件上传系统:完整实现指南
sqlite·html·fastapi
chenkangck5010 天前
Uvicorn 入门详解
python·fastapi
remandancy.h13 天前
FastAPI:(2)开启FastAPI
fastapi
里探14 天前
FastAPI的初步学习(Django用户过来的)
python·django·fastapi
从零开始学习人工智能14 天前
基于FastAPI与Selenium的智能开关状态管理系统实践
selenium·adb·fastapi
Python私教15 天前
FastAPI本地文档的定制技巧
fastapi
沛沛老爹17 天前
Celery+fastAPI/Flask实现高性能应用
python·flask·fastapi·celery·web框架集成
remandancy.h17 天前
FastAPI:(10)中间件与CORS
中间件·fastapi
浠寒AI18 天前
【FastAPI高级实战】结合查询参数与SQLModel Joins实现高效多表查询(分页、过滤、计数)
fastapi
浠寒AI21 天前
FastAPI核心解密:深入“路径操作”与HTTP方法,构建API的坚实骨架
网络协议·http·fastapi