Python FASTAPI 返回 XML Response

fastapi 目前对 XML 的支持还不是太好
工作需要返回XML的格式的数据,就研究了一下。

原来处理XML的时候 基本就用 ElementTree,所以就打包一个简单的 ElementTree的 FastAPI 的数据服务。

baidu 基本没用,最后看了一下 FastAPI的官网,找到一条 media_type='application/xml',解决问题

@app.post("/{platform}/abc")
async def process_item(item: Item = Depends(XmlBody(Item)), header: str = Header(None)):
    # print('process_item:',str(item))

    resp = FR_procContent.procContent(item)
    print('resp:',resp,'len(resp):',len(resp))

    # return resp
    # return XmlResponse(resp)
    return Response(ET.tostring(resp, encoding='UTF-8', method='xml'),media_type='application/xml')

这是读取 request 的body ,通过 Depends(XmlBody(Item))支持了对 XML 和 JSON 的同时的解析。

貌似simplexml load 会破坏 xml 的 namespace,所以,还是用了 ET

class XmlBody(Generic[T]):
    def __init__(self, model_class: Type[T]):
        self.model_class = model_class

    async def __call__(self, request: Request) -> T:
        # the following check is unnecessary if always using xml,
        # but enables the use of json too
        if request.headers.get("Content-Type") == "application/xml":
            body = await request.body()
            return response.text
        else:
            dict_data = await request.json()
        # return self.model_class.parse_obj(dict_data)
        return dict_data

 


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值