【发布时间】:2014-08-18 13:36:52
【问题描述】:
我使用 StringIO 创建了一个包含 xml 数据的文件对象,然后我用这个文件对象创建了一个 gzip 文件,我在使用 django 通过 HTTP 制作这个流时遇到了问题,文件大小并不总是固定的,有时它可能很大,这就是为什么我选择 HTTPStream 而不是普通的 HTTP 响应。我不知道如何发送文件长度,因为文件对象不可搜索。
谢谢你的帮助,干杯!
这是我的代码:
# Get the XML string
xml_string = get_xml_cebd(cebds)
# Write the xml string to the string io holder
cebd_xml_file.write(xml_string)
# Flush the xml file buffer
cebd_xml_file.flush()
# Create the Gzip file handler, with the StringIO in the fileobj
gzip_handler = gzip.GzipFile(
fileobj=cebd_xml_file,
filename=base_file_name + '.xml',
mode='wb'
)
# Write the XML data into the gziped file
gzip_handler.write(cebd_xml_file.getvalue())
gzip_handler.flush()
# Generate the response using the file warpper, content type: x-gzip
# Since this file can be big, best to use the StreamingHTTPResponse
# that way we can garantee that the file will be sent entirely
response = StreamingHttpResponse(
gzip_handler,
content_type='application/x-gzip'
)
# Add content disposition so the browser will download the file
response['Content-Disposition'] = ('attachment; filename=' +
base_file_name + '.xml.gz')
# Content size
gzip_handler.seek(0, os.SEEK_END)
response['Content-Length'] = gzip_handler.tell()
【问题讨论】:
标签: python django gzip http-streaming