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