本文整理汇总了Python中zipfile.ZipInfo类的典型用法代码示例。如果您正苦于以下问题:Python ZipInfo类的具体用法?Python ZipInfo怎么用?Python ZipInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ZipInfo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _render_zip
def _render_zip(self, req, filename, repos, data):
"""ZIP archive with all the added and/or modified files."""
new_rev = data['new_rev']
req.send_response(200)
req.send_header('Content-Type', 'application/zip')
req.send_header('Content-Disposition',
content_disposition('inline', filename + '.zip'))
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
buf = StringIO()
zipfile = ZipFile(buf, 'w', ZIP_DEFLATED)
for old_node, new_node, kind, change in repos.get_changes(
new_path=data['new_path'], new_rev=data['new_rev'],
old_path=data['old_path'], old_rev=data['old_rev']):
if kind == Node.FILE and change != Changeset.DELETE:
assert new_node
zipinfo = ZipInfo()
zipinfo.filename = new_node.path.strip('/').encode('utf-8')
# Note: unicode filenames are not supported by zipfile.
# UTF-8 is not supported by all Zip tools either,
# but as some do, I think UTF-8 is the best option here.
zipinfo.date_time = new_node.last_modified.utctimetuple()[:6]
zipinfo.external_attr = 0644 << 16L # needed since Python 2.5
zipinfo.compress_type = ZIP_DEFLATED
zipfile.writestr(zipinfo, new_node.get_content().read())
zipfile.close()
zip_str = buf.getvalue()
req.send_header("Content-Length", len(zip_str))
req.end_headers()
req.write(zip_str)
raise RequestDone
示例2: add
def add(self, member):
if (member.isdir):
return # FIXME Should be able to add empty directories
info = ZipInfo(member.name)
info.date_time = member.mtime
info.external_attr = member.perm << 16L
self.archive.writestr(info, member.data)
示例3: write_blob
def write_blob(self, path, blob, compression=ZIP_DEFLATED, mode=0644):
"""Add something to the zip without adding to manifest"""
zinfo = ZipInfo(path)
zinfo.external_attr = mode << 16L # set permissions
zinfo.compress_type = compression
zinfo.date_time = self.now
self.zipfile.writestr(zinfo, blob)
示例4: doTest
def doTest(self, expected_ext, files, *modules, **kw):
z = ZipFile(TEMP_ZIP, "w")
try:
for name, (mtime, data) in files.items():
zinfo = ZipInfo(name, time.localtime(mtime))
zinfo.compress_type = self.compression
z.writestr(zinfo, data)
z.close()
stuff = kw.get("stuff", None)
if stuff is not None:
# Prepend 'stuff' to the start of the zipfile
f = open(TEMP_ZIP, "rb")
data = f.read()
f.close()
f = open(TEMP_ZIP, "wb")
f.write(stuff)
f.write(data)
f.close()
sys.path.insert(0, TEMP_ZIP)
mod = __import__(".".join(modules), globals(), locals(),
["__dummy__"])
if expected_ext:
file = mod.get_file()
self.assertEquals(file, os.path.join(TEMP_ZIP,
*modules) + expected_ext)
finally:
z.close()
os.remove(TEMP_ZIP)
示例5: _render_zip
def _render_zip(self, req, filename, repos, diff):
"""ZIP archive with all the added and/or modified files."""
new_rev = diff.new_rev
req.send_response(200)
req.send_header('Content-Type', 'application/zip')
req.send_header('Content-Disposition', 'attachment;'
'filename=%s.zip' % filename)
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
buf = StringIO()
zipfile = ZipFile(buf, 'w', ZIP_DEFLATED)
for old_node, new_node, kind, change in repos.get_changes(**diff):
if kind == Node.FILE and change != Changeset.DELETE:
assert new_node
zipinfo = ZipInfo()
zipinfo.filename = new_node.path.encode('utf-8')
# Note: unicode filenames are not supported by zipfile.
# UTF-8 is not supported by all Zip tools either,
# but as some does, I think UTF-8 is the best option here.
zipinfo.date_time = time.gmtime(new_node.last_modified)[:6]
zipinfo.compress_type = ZIP_DEFLATED
zipfile.writestr(zipinfo, new_node.get_content().read())
zipfile.close()
buf.seek(0, 2) # be sure to be at the end
req.send_header("Content-Length", buf.tell())
req.end_headers()
req.write(buf.getvalue())
示例6: export
def export():
name = request.form.get('name')
settings = loads(open(PATH_SETTINGS + name + '.json', 'rb').read())
# Build list of needed resources
resources = []
for listener in settings.get('listeners', []):
for effect in listener.get('effects', []):
resource = effect.get('resource', {}).get('source')
if type(resource) is list:
resources = resources + resource
else:
resources.append(resource)
# Create ZIP with all files
memory_file = BytesIO()
with ZipFile(memory_file, 'w') as zf:
# Resources
for resource in resources:
path = PATH_FILES + resource
data = ZipInfo('files/' + resource)
data.compress_type = ZIP_DEFLATED
zf.writestr(data, open(path, 'rb').read())
# Config
data = ZipInfo('settings/' + name + '.json')
data.compress_type = ZIP_DEFLATED
zf.writestr(data, open(PATH_SETTINGS + name + '.json', 'rb').read())
memory_file.seek(0)
return send_file(memory_file, attachment_filename=name + '.zip', as_attachment=True)
示例7: handle
def handle(self, *args, **options):
options['platform'] = options['platform'].lower() # normalize
if options['platform'] not in ["all", "linux", "macos", "darwin", "windows"]:
raise CommandError("Unrecognized platform: %s; will include ALL files." % options['platform'])
# Step 1: recursively add all static files
kalite_base = os.path.realpath(settings.PROJECT_PATH + "/../")
files_dict = recursively_add_files(dirpath=kalite_base, **options)
# Step 2: Add a local_settings.py file.
# For distributed servers, this is a copy of the local local_settings.py,
# with a few properties (specified as command-line options) overridden
ls_file = create_local_settings_file(location=os.path.realpath(kalite_base+"/kalite/local_settings.py"), server_type=options['server_type'], locale=options['locale'])
files_dict[ls_file] = { "dest_path": "kalite/local_settings.py" }
# Step 3: select output file.
if options['file']=="__default__":
options['file'] = create_default_archive_filename(options)
# Step 4: package into a zip file
with ZipFile(options['file'], "w", ZIP_DEFLATED if options['compress'] else ZIP_STORED) as zfile:
for srcpath,fdict in files_dict.items():
if options['verbosity'] >= 1:
print "Adding to zip: %s" % srcpath
# Add without setting exec perms
if os.path.splitext(fdict["dest_path"])[1] != ".sh":
zfile.write(srcpath, arcname=fdict["dest_path"])
# Add with exec perms
else:
info = ZipInfo(fdict["dest_path"])
info.external_attr = 0755 << 16L # give full access to included file
with open(srcpath, "r") as fh:
zfile.writestr(info, fh.read())
示例8: dump
def dump(self, fp):
"""Dump the plugin as package into the filepointer or file."""
from zipfile import ZipFile, ZipInfo
f = ZipFile(fp, 'w')
# write all files into a "pdata/" folder
offset = len(self.path) + 1
for dirpath, dirnames, filenames in walk(self.path):
# don't recurse into hidden dirs
for i in range(len(dirnames)-1, -1, -1):
if dirnames[i].startswith('.'):
del dirnames[i]
for filename in filenames:
if filename.endswith('.pyc') or \
filename.endswith('.pyo'):
continue
f.write(path.join(dirpath, filename),
path.join('pdata', dirpath[offset:], filename))
# add the package information files
for name, data in [('ZINE_PLUGIN', self.name),
('ZINE_PACKAGE', PACKAGE_VERSION)]:
zinfo = ZipInfo(name, localtime(time()))
zinfo.compress_type = f.compression
zinfo.external_attr = (33188 & 0xFFFF) << 16L
f.writestr(zinfo, str(data))
f.close()
示例9: createZipArchive
def createZipArchive(self, source, destination, exclude=None):
"""
Create a zip file at `destination` based on files from `source`.
"""
"""
Create a zip file at `destination` based on files from `source`.
"""
if exclude is None:
exclude = []
source_path = self.fs.join(source)
parent_path = os.path.dirname(source_path)
archivename = self.fs.join(destination)
with closing(ZipFile(archivename, 'w', ZIP_DEFLATED)) as z:
for root, dirs, files in os.walk(source_path):
# Write all files.
for fn in files:
if fn in exclude:
continue
absolute_filename = os.path.join(root, fn)
zip_filename = absolute_filename[len(parent_path):]
# See http://bugs.python.org/issue1734346
# for adding unicode support.
z.write(str(absolute_filename), str(zip_filename))
# For empty folders, we need to create a special ZipInfo
# entry.
# 16 works, but some places suggest using 48.
if not files and not dirs:
foldername = root[len(parent_path):] + '/'
zip_info = ZipInfo(foldername)
zip_info.external_attr = 16
z.writestr(zip_info, "")
示例10: add_file
def add_file(self, zf, path, name):
with open(path, 'rb') as f:
raw = f.read()
self.h.update(raw)
zi = ZipInfo(name)
zi.external_attr = 0o444 << 16
zf.writestr(zi, raw)
示例11: _write
def _write (self, zname, str) :
now = datetime.utcnow ().timetuple ()
info = ZipInfo (zname, date_time = now)
info.create_system = 0 # pretend to be fat
info.compress_type = ZIP_DEFLATED
self.ozip.writestr (info, str)
self.written [zname] = 1
示例12: validate
def validate(self, data):
url = data["file_url"]
order_hash = data["order_hash"]
if url and order_hash:
try:
# get file name and save
file_name = os.path.basename(os.path.realpath(url))
urllib.urlretrieve(url, file_name)
# get data from file
epub_old = ZipFile(file_name, "r")
txt = epub_old.read("META-INF/container.xml")
epub_old.close()
# rewrite file and add comment
epub_new = ZipFile(file_name, "w")
epub_new.writestr("mimetype", "application/epub+zip")
info = ZipInfo("META-INF/container.xml", date_time=time.localtime(time.time()))
info.comment = "%s at %s" % (order_hash, time.strftime("%d/%m/%Y"))
epub_new.writestr(info, txt)
epub_new.close()
except:
raise serializers.ValidationError("Some error with file or not correct url")
return file_name
return data
示例13: _render_zip
def _render_zip(self, req, repos, chgset):
"""ZIP archive with all the added and/or modified files."""
req.send_response(200)
req.send_header('Content-Type', 'application/zip')
req.send_header('Content-Disposition', 'attachment;'
'filename=Changeset%s.zip' % chgset.rev)
req.end_headers()
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
buf = StringIO()
zipfile = ZipFile(buf, 'w', ZIP_DEFLATED)
for path, kind, change, base_path, base_rev in chgset.get_changes():
if kind == Node.FILE and change != Changeset.DELETE:
node = repos.get_node(path, chgset.rev)
zipinfo = ZipInfo()
zipinfo.filename = node.path
zipinfo.date_time = time.gmtime(node.last_modified)[:6]
zipinfo.compress_type = ZIP_DEFLATED
zipfile.writestr(zipinfo, node.get_content().read())
zipfile.close()
req.write(buf.getvalue())
示例14: testZipImporterMethodsInSubDirectory
def testZipImporterMethodsInSubDirectory(self):
packdir = TESTPACK + os.sep
packdir2 = packdir + TESTPACK2 + os.sep
files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
z = ZipFile(TEMP_ZIP, "w")
try:
for name, (mtime, data) in files.items():
zinfo = ZipInfo(name, time.localtime(mtime))
zinfo.compress_type = self.compression
z.writestr(zinfo, data)
z.close()
zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
self.assertEquals(zi.archive, TEMP_ZIP)
self.assertEquals(zi.prefix, packdir)
self.assertEquals(zi.is_package(TESTPACK2), True)
zi.load_module(TESTPACK2)
self.assertEquals(zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
self.assertEquals(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
mod_name = TESTPACK2 + os.sep + TESTMOD
mod = __import__(module_path_to_dotted_name(mod_name))
self.assertEquals(zi.get_source(TESTPACK2), None)
self.assertEquals(zi.get_source(mod_name), None)
finally:
z.close()
os.remove(TEMP_ZIP)
示例15: _collect_infos
def _collect_infos(dirname):
""" Utility function used by ExplodedZipFile to generate ZipInfo
entries for all of the files and directories under dirname """
for r, _ds, fs in walk(dirname):
if not islink(r) and r != dirname:
i = ZipInfo()
i.filename = join(relpath(r, dirname), "")
i.file_size = 0
i.compress_size = 0
i.CRC = 0
yield i.filename, i
for f in fs:
df = join(r, f)
relfn = relpath(join(r, f), dirname)
if islink(df):
pass
elif isfile(df):
i = ZipInfo()
i.filename = relfn
i.file_size = getsize(df)
i.compress_size = i.file_size
i.CRC = file_crc32(df)
yield i.filename, i
else:
# TODO: is there any more special treatment?
pass