我有一个 Django 应用程序,它创建一个 .tar.gz 文件以供下载。在本地,我在我的开发机器 Python 2.7 和远程开发服务器 Python 2.6.6 上运行。当我下载文件时,我可以通过 Mac Finder / 命令行打开并查看内容。但是,Python 2.7 不喜欢在我的远程开发服务器上创建的 .tar.gz 文件……我需要将这些文件上传到使用 Python 解压/解析档案的站点。我怎样才能调试出了什么问题?在 Python 外壳中:
>>> tarfile.is_tarfile('myTestFile_remote.tar.gz')
False
>>> tarfile.is_tarfile('myTestFile_local.tar.gz')
True
>>> f = tarfile.open('myTestFile_remote.tar.gz', 'r:gz')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.py", line 1678, in open
return func(name, filemode, fileobj, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.py", line 1727, in gzopen
**kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.py", line 1705, in taropen
return cls(name, mode, fileobj, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.py", line 1574, in __init__
self.firstmember = self.next()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.py", line 2331, in next
raise ReadError(str(e))
tarfile.ReadError: invalid header
从这个 SO question,我也尝试gzip -t
对远程文件运行,但没有输出(我相信这意味着文件是好的)。从this other SO question,我跑了file myTestFile_remote.tar.gz
,我相信输出显示正确的文件格式:
myTestFile_remote.tar.gz: gzip compressed data, from Unix
我不太确定我还能尝试什么。似乎抛出异常是因为我的 tarfile 有self.offset == 0
,但我不知道这意味着什么,而且我不明白如何创建 tarfile 以免发生这种情况。欢迎提出建议...
不确定什么代码在这里有用。我创建和返回 tarfile 的代码:
zip_filename = '%s_%s.tar.gz' % (course.name, course.url)
s = cStringIO.StringIO()
zf = tarfile.open(zip_filename, mode='w:gz', fileobj=s)
<add a bunch of stuff>
zipped = zip_collection(zip_data)
zf.close()
if zipped:
response = HttpResponse(content_type="application/tar")
response['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
s.seek(0, os.SEEK_END)
response.write(s.getvalue())
------ 更新 ------ 根据这篇 SO 帖子,我还验证了远程文件是一个 tar.gz 文件,tar -zxvf myTestFile_remote.tar.gz
从命令行使用。该文件提取得很好。