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

相关推荐
黑金IT4 天前
WebSocket vs. Server-Sent Events:选择最适合你的实时数据流技术
网络·python·websocket·网络协议·fastapi
黑金IT4 天前
FastAPI 应用安全加固:HTTPSRedirectMiddleware 中间件全解析
安全·中间件·fastapi
写bug如流水5 天前
【FastAPI】实现服务器向客户端发送SSE(Server-Sent Events)广播
服务器·python·fastapi
黑金IT5 天前
从单体到微服务:FastAPI ‘挂载’子应用程序的转变
微服务·架构·fastapi
不良人龍木木6 天前
sqlalchemy FastAPI 前端实现数据库增删改查
前端·数据库·fastapi
写bug如流水6 天前
【FastAPI】离线使用Swagger UI 或 国内网络如何快速加载Swagger UI
ui·fastapi·命令模式
布响哒公8 天前
用python fastapi写一个http接口,使ros2机器人开始slam toolbox建图
python·机器人·fastapi
_.Switch9 天前
Python Web 框架篇:Flask、Django、FastAPI介绍及其核心技术
开发语言·前端·后端·python·django·flask·fastapi
黑金IT10 天前
深入FastAPI:掌握使用多个关联模型的高级用法[Union类型]
python·fastapi
黑金IT11 天前
深入理解FastAPI的response_model:自动化数据验证与文档生成
python·fastapi