FastAPI学习-18.Response 返回 XML 格式

FastAPI中的XML响应处理与Response类详解,
本文介绍了如何在FastAPI中创建一个返回XML内容的自定义Response,包括设置media_type为application/xml,以及Response类的参数和使用注意事项,强调了响应未经校验和转换的特性,同时提到了与OpenAPI响应文档的关系。

前言

假设你想要返回一个 XML 响应。
你可以把你的 XML 内容放到一个字符串中,放到一个 Response 中,然后返回。

Response 自定义返回

可以把 XML 内容放到一个字符串中,放到一个 Response 中,设置media_type="application/xml"

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/xml/")
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")

Response 类接受如下参数:

  • content - 一个 str 或者 bytes
  • status_co
### 解决FastAPI返回XML字符串时出现的`'str' object is not callable`错误 在FastAPI中,当尝试直接返回一个XML字符串时,可能会遇到`'str' object is not callable`的错误。这是因为FastAPI默认将返回值视为JSON响应,并且内部机制可能无法正确处理非标准的返回类型[^2]。 为了解决这个问题,可以使用`Response`类或其子类(如`PlainTextResponse`或自定义响应)来明确指定返回的内容类型。以下是一个完整的解决方案: #### 使用`PlainTextResponse`返回XML字符串 通过`fastapi.responses`模块中的`PlainTextResponse`,可以明确指定返回的内容类型为`text/xml`,从而避免FastAPI将其误认为是可调用对象。 ```python from fastapi import FastAPI from fastapi.responses import PlainTextResponse app = FastAPI() @app.get("/xml", response_class=PlainTextResponse) def get_xml(): xml_content = """<?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>""" return xml_content ``` 在此示例中,`response_class=PlainTextResponse`确保了返回的内容被正确识别为纯文本,并且可以通过设置`Content-Type: text/xml`来进一步优化响应头[^3]。 #### 自定义XML响应类 如果需要更灵活的控制,可以创建一个自定义的响应类来专门处理XML数据: ```python from fastapi import FastAPI from fastapi.responses import Response app = FastAPI() class XMLResponse(Response): media_type = "application/xml" def render(self, content): return content.encode("utf-8") @app.get("/custom_xml") def get_custom_xml(): xml_content = """<?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>""" return XMLResponse(content=xml_content) ``` 此方法通过继承`Response`类并重写`render`方法,能够更加精确地控制XML的编码和格式化[^4]。 #### 错误原因分析 `'str' object is not callable`的错误通常发生在FastAPI试图将返回值作为函数调用时。这可能是由于返回值没有被正确包装为响应对象,或者路由装饰器未正确配置导致的。例如,如果直接返回一个字符串而不指定响应类,FastAPI可能会尝试调用该字符串,从而引发上述错误[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值