Python 流HTTPS获取在GZ内加载和解析XML
在从HTTPS获取XML流的过程中,我需要在GZ内部处理(如果可能的话)XML。 如果保存,结果文件非常大:23 GB 现在,我使用流媒体从HTTPS获取数据,并将文件保存到存储器中。由于Python脚本需要作为批处理作业部署在AWS上,因此存储不是一个选项。我更喜欢不使用S3服务作为存储 算法应为:Python 流HTTPS获取在GZ内加载和解析XML,python,xml,amazon-web-services,stream,gzip,Python,Xml,Amazon Web Services,Stream,Gzip,在从HTTPS获取XML流的过程中,我需要在GZ内部处理(如果可能的话)XML。 如果保存,结果文件非常大:23 GB 现在,我使用流媒体从HTTPS获取数据,并将文件保存到存储器中。由于Python脚本需要作为批处理作业部署在AWS上,因此存储不是一个选项。我更喜欢不使用S3服务作为存储 算法应为: while stream GET HTTPS in chunk: - get xml chunk from GZ chunk - process xml chunk 例如,XML具
while stream GET HTTPS in chunk:
- get xml chunk from GZ chunk
- process xml chunk
例如,XML具有下一个结构:
<List>
<Property>
<id = '123>
<PhotoProperties>
<Photo>
<url = 'https://www.url.com/photo/1.jpg>
</Photo>
</PhotoProperties>
</Property>
<Property>...</Property>
是的,这是可能的。
关键是所有操作都支持流式传输,并且有库可以做到这一点:
- 用于流式传输内容
- 可用于解压缩gzip流
- 关于xml解析,关键是要了解解析xml文件有两种主要方法:
- DOM解析:当完整的xml可以存储在内存中时非常有用。这允许轻松地操作和发现xml内容
- SAX解析:在xml无法存储在内存中的情况下非常有用,例如,因为它太大,或者因为您想在读取整个流之前开始处理。这就是你需要的。可以用于此
<?xml version="1.0" encoding="UTF-8"?>
<List>
<Property id = "123">
<PhotoProperties>
<Photo url = "https://www.url.com/photo/1.jpg"/>
</PhotoProperties>
</Property>
<Property id = "456">
<PhotoProperties>
<Photo url = "https://www.url.com/photo/2.jpg"/>
</PhotoProperties>
</Property>
</List>
是的,这是可能的。
关键是所有操作都支持流式传输,并且有库可以做到这一点:
- 用于流式传输内容
- 可用于解压缩gzip流
- 关于xml解析,关键是要了解解析xml文件有两种主要方法:
- DOM解析:当完整的xml可以存储在内存中时非常有用。这允许轻松地操作和发现xml内容
- SAX解析:在xml无法存储在内存中的情况下非常有用,例如,因为它太大,或者因为您想在读取整个流之前开始处理。这就是你需要的。可以用于此
<?xml version="1.0" encoding="UTF-8"?>
<List>
<Property id = "123">
<PhotoProperties>
<Photo url = "https://www.url.com/photo/1.jpg"/>
</PhotoProperties>
</Property>
<Property id = "456">
<PhotoProperties>
<Photo url = "https://www.url.com/photo/2.jpg"/>
</PhotoProperties>
</Property>
</List>
import urllib.request
import zlib
import xml.parsers.expat
from dataclasses import dataclass
URL='https://some.url.com/pictures.xml'
@dataclass
class Picture:
id: int
url: str
class ParseHandler:
def __init__(self):
self.currentPicture = None
def start_element(self, name, attrs):
if (name=='Property'):
self.currentPicture = Picture(attrs['id'], None)
elif (name=='Photo'):
self.currentPicture.url=attrs['url']
def end_element(self, name):
if (name=='Property'):
print(self.currentPicture)
self.currentPicture=None
handler = ParseHandler()
parser = xml.parsers.expat.ParserCreate()
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
decompressor = zlib.decompressobj(32 + zlib.MAX_WBITS)
with urllib.request.urlopen(URL) as stream:
for gzchunk in stream:
xmlchunk = decompressor.decompress(gzchunk)
parser.Parse(xmlchunk)