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

相关推荐
周杰伦_Jay19 小时前
【Python后端API开发对比】FastAPI、主流框架Flask、Django REST Framework(DRF)及高性能框架Tornado
数据结构·人工智能·python·django·flask·fastapi·tornado
悟乙己1 天前
使用 RAG、LangChain、FastAPI 和 Streamlit 构建 Text-to-SQL 聊天机器人
sql·langchain·fastapi
weixin_307779132 天前
用Python和FastAPI构建一个完整的企业级AI Agent微服务脚手架
python·fastapi·web app
逐云者1233 天前
使用 FastAPI 构建大模型应用的系统教程(工程化实战指南)
大模型·fastapi·router·分层架构·算法工程·算法服务
铁锹少年3 天前
当多进程遇上异步:一次 Celery 与 Async SQLAlchemy 的边界冲突
分布式·后端·python·架构·fastapi
钱彬 (Qian Bin)8 天前
项目实践6—全球证件智能识别系统(Qt客户端开发+FastAPI后端人工智能服务开发)
人工智能·qt·fastapi·证件识别
游九尘9 天前
uniapp安卓端+ fastapi(后端)获取到设备的ip
uni-app·fastapi
Cherry Zack13 天前
FastAPI 入门指南 :基础概念与核心特性
开发语言·python·fastapi·1024程序员节
深兰科技14 天前
深兰科技法务大模型亮相,推动律所文书处理智能化
人工智能·scrapy·beautifulsoup·scikit-learn·pyqt·fastapi·深兰科技