|
1 | 1 | """Provides a general interface to a `physical` OPC package, such as a zip file.""" |
2 | 2 |
|
3 | 3 | import os |
4 | | -from zipfile import ZIP_DEFLATED, ZipFile, is_zipfile |
| 4 | +import zlib |
| 5 | +from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, is_zipfile |
5 | 6 |
|
6 | 7 | from docx.opc.exceptions import PackageNotFoundError |
7 | 8 | from docx.opc.packuri import CONTENT_TYPES_URI |
@@ -73,14 +74,25 @@ class _ZipPkgReader(PhysPkgReader): |
73 | 74 |
|
74 | 75 | def __init__(self, pkg_file): |
75 | 76 | super(_ZipPkgReader, self).__init__() |
76 | | - self._zipf = ZipFile(pkg_file, "r") |
| 77 | + try: |
| 78 | + self._zipf = ZipFile(pkg_file, "r") |
| 79 | + except (BadZipFile, zlib.error, EOFError, RuntimeError): |
| 80 | + raise PackageNotFoundError( |
| 81 | + "Package not found or not a valid zip archive: '%s'" % pkg_file |
| 82 | + ) |
77 | 83 |
|
78 | 84 | def blob_for(self, pack_uri): |
79 | 85 | """Return blob corresponding to `pack_uri`. |
80 | 86 |
|
81 | 87 | Raises |ValueError| if no matching member is present in zip archive. |
82 | 88 | """ |
83 | | - return self._zipf.read(pack_uri.membername) |
| 89 | + try: |
| 90 | + return self._zipf.read(pack_uri.membername) |
| 91 | + except (KeyError, zlib.error, EOFError, RuntimeError): |
| 92 | + raise ValueError( |
| 93 | + "Could not read member '%s' from package (corrupt or missing?)" |
| 94 | + % pack_uri.membername |
| 95 | + ) |
84 | 96 |
|
85 | 97 | def close(self): |
86 | 98 | """Close the zip archive, releasing any resources it is using.""" |
|
0 commit comments