本文整理汇总了Python中zipfile.ZipFile.testzip方法的典型用法代码示例。如果您正苦于以下问题:Python ZipFile.testzip方法的具体用法?Python ZipFile.testzip怎么用?Python ZipFile.testzip使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zipfile.ZipFile
的用法示例。
在下文中一共展示了ZipFile.testzip方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def check(self, fileinfo, logical_component, installation_method):
## Must be a zip file
try:
zf = ZipFile(fileinfo)
zf.testzip()
except BadZipfile, e:
raise forms.ValidationError('File is not an EAR or WAR archive or is corrupted: ' + str(e))
示例2: _modify_zip_file
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def _modify_zip_file(self, zip_path, filename, replacement_content=None):
"""
Replace the contents of a file inside a ZIP-container. The original file
will not be overwritten. A BytesIO() file will be returned containing
the new ZIP-container with the file replaced.
:param zip_path The path to the ZIP-File to be modified
:param filename Filename inside the container to be modified
:param replacement_content The new container which will be stored in `filename`
:return BytesIO contain the modified zip file.
"""
vuln_zipfile = BytesIO()
zw = ZipFile(vuln_zipfile, 'w')
zr = ZipFile(zip_path)
names_to_copy = set(zr.namelist()) - {filename, }
for name in names_to_copy:
content = zr.read(name)
zw.writestr(name, content)
if replacement_content:
zw.writestr(filename, replacement_content)
zw.close()
vuln_zipfile.seek(0)
x = ZipFile(vuln_zipfile, 'r')
self.assertEqual(x.testzip(), None)
vuln_zipfile.seek(0)
return vuln_zipfile
示例3: unzipBuild
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def unzipBuild(self, sourceFile, targetFolder):
from zipfile import ZipFile
import os, shutil
sourceFile = str(sourceFile).replace("\\", "/")
zf = ZipFile(file=sourceFile)
self.logger.debug("Go to test source zip file")
zf.testzip()
# Empty target Folder
try:
shutil.rmtree(targetFolder)
self.logger.debug("Remove folder " + targetFolder)
except Exception, e:
self.logger.debug(e)
示例4: force_create
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def force_create(self, archivo, **kw):
"""Sube una entrega en lugar de un alumno"""
instancia = kw['instancia']
entregador = kw['entregador']
archivo = archivo.file.read()
try:
zfile = ZipFile(StringIO(archivo), 'r')
except BadZipfile:
flash(_(u'El archivo ZIP no es válido'))
raise redirect('force_new', kw)
if zfile.testzip() is not None:
flash(_(u'El archivo ZIP tiene errores de CRC'))
raise redirect('force_new',kw)
entregador_id = int(entregador)
instancia = InstanciaDeEntrega.get(int(instancia))
if instancia.ejercicio.grupal:
entregador = Grupo.get(entregador_id)
else:
entregador = AlumnoInscripto.get(entregador_id)
kw['instancia'] = instancia
kw['archivos'] = archivo
kw['entregador'] = entregador
kw['observaciones'] = 'Entrega realizada manualmente por el docente %s' % identity.current.user.shortrepr()
Entrega(**kw)
flash('Se creo una nueva entrega')
raise redirect('list')
示例5: validate_zip_integrity
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def validate_zip_integrity(uploaded_file):
"""
If uploaded file is a .zip archive, check its integrity and the
integrity of the files it contains.
In case of a corrupted archive the `ZipFile` constructor raises
IOError. To check the integrity of the files contained in the
archive, the `ZipFile.testzip()` function is used.
If the uploaded file appears to be a .zip archive (because its
extension is `.zip`), but actually isn't, the `ZipFile`
constructor raises `BadZipFile`. Because this case is covered by
the MIME type validator, the function does not raise a
ValidationError in this case.
"""
if uploaded_file.name.endswith("zip"):
corrupted_file = None
try:
archive = ZipFile(get_tmp_path(uploaded_file.name))
corrupted_file = archive.testzip()
except IOError:
raise ValidationError(UploadFormErrors.ZIP_INTEGRITY)
except BadZipFile:
pass
if corrupted_file:
raise ValidationError(UploadFormErrors.FILES_INTEGRITY)
示例6: parse_zipfile_metadata
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def parse_zipfile_metadata(uploaded_file):
"""
Given a file, extract out the metadata.json, parse, and return it.
"""
try:
zipfile = ZipFile(uploaded_file, 'r')
except (BadZipfile, zlib.error):
raise InvalidExtensionData("Invalid zip file")
if zipfile.testzip() is not None:
raise InvalidExtensionData("Invalid zip file")
total_uncompressed = sum(i.file_size for i in zipfile.infolist())
if total_uncompressed > 5*1024*1024: # 5 MB
raise InvalidExtensionData("Zip file is too large")
try:
metadata = json.load(zipfile.open('metadata.json', 'r'))
except KeyError:
# no metadata.json in archive, raise error
raise InvalidExtensionData("Missing metadata.json")
except ValueError:
# invalid JSON file, raise error
raise InvalidExtensionData("Invalid JSON data")
zipfile.close()
return metadata
示例7: test_tutorials_presentation
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def test_tutorials_presentation(self):
section = Section.objects.get(name='Tutorials')
schedule = Schedule.objects.get(section=section)
prop_kind = ProposalKind.objects.get(slug='tutorial')
proposal = PyConTutorialProposalFactory(
kind=prop_kind,
)
day = Day.objects.create(schedule=schedule, date=date.today())
kind = SlotKind.objects.create(schedule=schedule, label="Foo")
slot = Slot.objects.create(
day=day,
kind=kind,
start=now().time(),
end=now().time(),
)
pres = PresentationFactory(
title=proposal.title,
abstract=proposal.abstract,
section=section,
slot=slot,
cancelled=False,
proposal_base=proposal,
)
rsp = self.client.get(self.url)
self.assertEqual(OK, rsp.status_code)
self.assertEqual('attachment; filename=program_export.zip', rsp['Content-Disposition'])
zipfile = ZipFile(StringIO(rsp.content), "r")
# Check out the zip - testzip() returns None if no errors found
self.assertIsNone(zipfile.testzip())
fname = "program_export/presentations/csv/tutorials.csv"
file_contents = zipfile.open(fname, "U").read().decode('utf-8')
self.assertIn(pres.title, file_contents)
self.assertIn(pres.abstract, file_contents)
示例8: _get_carparks_xml_from_zip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def _get_carparks_xml_from_zip(url=CARPARKS_ZIP_URL, index_xml=INDEX_XML_FILE_NAME):
res = request.urlopen(url=url)
# Validate a successful HTTP call with status 200.
if not res.status == 200:
raise Exception('Call to \'{0!s}\' failed with status code {1!s}.'.format(url, res.status))
# Convert the downloaded byte stream to a file-like in-memory object.
zip_file = BytesIO(res.read())
# Validate the file-like object contains a valid zip file.
if not is_zipfile(zip_file):
raise Exception('The URL \'{0!s}\' did not return a valid zip file.'.format(url))
# Convert to an actual ZipFile object.
zip = ZipFile(zip_file, 'r')
# Fail if the returned zip file is corrupt.
if zip.testzip():
raise Exception('Zip file from \'{0!s}\' was corrupt.'.format(url))
# Create a list of filenames to process.
xml_filenames = _get_filenames_from_index_xml(index=zip.read(index_xml))
# Validate there is at least 1 file to process.
if len(xml_filenames) < 1:
raise Exception('No XML files listed in {0!s}!'.format(index_xml))
# Create and populate a dictionary with filenames and contents.
return_str_xmls = dict()
for filename in xml_filenames:
return_str_xmls[filename] = zip.read(filename)
# Return the dictionary.
return return_str_xmls
示例9: checkZip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def checkZip(file, purge=False, verbose=False):
"""
Use Zip to see if the file is valid and prints the name of failed files to
stdout. If purge is set to true it will also delete the file.
In verbose mode it will print a dot for every good file as well.
"""
global zip
try:
zip = ZipFile(file)
if zip.testzip() == None:
if verbose:
sys.stdout.write(".")
sys.stdout.flush()
else:
if verbose:
print()
print("File", file, "failed with corrupted files")
if purge:
os.remove(file)
except BadZipfile:
if verbose:
print()
print("File %s failed with flying colors. Not a valid zip." % file)
if purge:
os.remove(file)
finally:
zip.close()
示例10: update
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def update(self, update):
dpath = self.xplanedir + '/Resources/Downloads'
installpath = self.xplanedir + '/Resources/plugins/PythonScripts'
# Broadcast message to all plugins
XPLMSendMessageToPlugin(XPLM_NO_PLUGIN_ID, 0x8000000 | 8090 , long(1))
PI_SendMessageToScript(self, None, 0x8000000 | 8090, 1)
sleep(1)
if not os.path.exists(dpath):
os.mkdir(dpath)
if update['update_type'] == 'direct' and update['update_filename']:
urllib.urlretrieve(update['update_url'], dpath + '/' + update['update_filename'])
copy(dpath + '/' + update['update_filename'], installpath + '/' + update['update_filename'])
print dpath + '/' + update['update_filename'], installpath + '/' + update['update_filename']
elif update['update_type'] == 'zip':
zipfile = dpath + '/._xpjpcUPDATE.zip'
# Download update
urllib.urlretrieve(update['update_url'], zipfile)
zip = ZipFile(zipfile, 'r')
# Check zip file
if not zip.testzip():
# Unzip
unzipdir = dpath + '/' + zip.namelist()[0]
zip.extractall(dpath)
zip.close()
# Move files
self.tcopy(unzipdir, installpath)
rmtree(unzipdir)
os.remove(zipfile)
示例11: test_archive
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def test_archive(self):
for (example, ExampleDataset) in examples.examples:
filename = create_archive(example.data_csv, example.sli_manifest)
zip_file = ZipFile(filename, "r")
self.assertEquals(None, zip_file.testzip())
self.assertEquals(zip_file.namelist(), ['data.csv', 'upload_info.json'])
zip_file.close()
os.remove(filename)
示例12: test_zipped_excluded_directory
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def test_zipped_excluded_directory(self):
zippedRoot = self.get_zipped_root('1/')
expected_entries = ['2/2-1/2-1.txt']
zf = ZipFile(zippedRoot)
self.assertTrue(zf.testzip() is None)
for elem in expected_entries:
self.assertTrue(elem in zf.namelist())
self.assertEqual(len(expected_entries), len(zf.namelist()))
zf.close()
示例13: decrypt_data
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def decrypt_data(encrypted_string, key, string_file_mode=False, key_file_mode=False):
"""Method that takes either the key or the encrypted string as a
string or can the key and encrypted string a as file and decrypts
the string using the provided string. NOTE** In order to use the the key.dat file
you must first also be able to unzip it using a password."""
print("Starting Decryption...")
if key_file_mode:
if ".zip" in key:
zf = ZipFile(key)
try:
if zf.testzip() == None:
ZipFile(key).extractall()
print("Successfully extracted, please use the key file \
with the .dat extension file as your key and try again.\n")
exit(0)
except:
print("Key.zip is encrypted!\n")
_unzip_file(key, input("Please enter the password to unzip the key file and try again.\n"))
else:
my_key = key
with open(my_key, 'r') as key_data:
my_key = key_data.read()
else:
my_key = key
if string_file_mode:
my_string = encrypted_string
with open(my_string, 'r') as string_data:
my_string = string_data.read()
else:
my_string = encrypted_string
my_string_num_list = my_string
my_key_num_list = _string_converter(my_key)[2:]
print("Decrypting file...please wait, this may take a while depending on file size.")
decrypt_list = []
for j in range(2, len(my_string_num_list)):
index = j % len(my_key_num_list)
decrypt_list.append(int(my_string_num_list[j]) ^ int(my_key_num_list[index]))
decrypted_string = int("0b" + "".join((str(i) for i in decrypt_list)), 2)
if version_info >= (3, 0):
message = decrypted_string.to_bytes((decrypted_string.bit_length() + 7) // 8, 'big').decode()
else:
message = unhexlify('%x' % decrypted_string)
with open("decrypted_message.txt", 'w') as out_message:
out_message.write(message)
print("Decryption Complete.")
return message
示例14: test_003_user_can_download_credentials
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def test_003_user_can_download_credentials(self):
buf = self.get_signed_zip(test_username)
output = open(ZIP_FILENAME, 'w')
output.write(buf)
output.close()
zip = ZipFile(ZIP_FILENAME, 'a', ZIP_DEFLATED)
bad = zip.testzip()
zip.close()
self.failIf(bad)
示例15: test_upload
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import testzip [as 别名]
def test_upload(self):
example = examples.examples[0][0]
connection = Connection(username, password, debug=0)
dir_name = connection.webdav.upload(example.data_csv, example.sli_manifest)
self.assert_(len(dir_name) > 0)
self.assert_(connection.webdav.request('/uploads/%s' % dir_name))
uploaded_file = connection.webdav.request('/uploads/%s/upload.zip' % dir_name)
tmp_file = write_tmp_file(uploaded_file.read())
zip_file = ZipFile(tmp_file, "r")
self.assertEquals(None, zip_file.testzip())
self.assertEquals(zip_file.namelist(), ['data.csv', 'upload_info.json'])
zip_file.close()
os.remove(tmp_file)