将大型 XML 文件直接从 GridFS 流式传输到 xmltodict 解析

问题描述 投票:0回答:0

我正在使用 Motor 进行异步 MongoDB 操作。我有一个 gridfs 存储,我以 8 MB 的块存储大型 XML 文件(通常大小超过 30 MB)。我想使用 xmltodict 增量解析 XML 文件。 这是我的代码的样子。

async def read_file(file_id):
    gfs_out: AsyncIOMotorGridOut = await gfs_bucket.open_download_stream(file_id)

    tmpfile = tempfile.SpooledTemporaryFile(mode="w+b")
    while data := await gfs_out.readchunk():
        tmpfile.write(data)

    xmltodict.parse(tmpfile)

我是把所有的chunk一个一个的拉出来存到内存中的一个临时文件中,然后通过xmltodict解析整个文件。理想情况下,我希望逐步解析它,因为我不需要从一开始就需要整个 xml 对象。

xmltodict 的文档建议我们可以添加自定义处理程序来解析流,就像这个例子:

>>> def handle_artist(_, artist):
...     print(artist['name'])
...     return True
>>> 
>>> xmltodict.parse(GzipFile('discogs_artists.xml.gz'),
...     item_depth=2, item_callback=handle_artist)
A Perfect Circle
Fantômas
King Crimson
Chris Potter
...

但问题在于它需要一个具有同步

read()
方法的类文件对象,而不是协程。有什么办法可以实现吗?任何帮助将不胜感激。

python mongodb python-asyncio gridfs xmltodict
© www.soinside.com 2019 - 2024. All rights reserved.