本文整理汇总了Python中zipfile.ZipInfo.date_time方法的典型用法代码示例。如果您正苦于以下问题:Python ZipInfo.date_time方法的具体用法?Python ZipInfo.date_time怎么用?Python ZipInfo.date_time使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zipfile.ZipInfo
的用法示例。
在下文中一共展示了ZipInfo.date_time方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_zipinfo
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def create_zipinfo(filename, mtime=None, dir=False, executable=False, symlink=False,
comment=None):
"""Create a instance of `ZipInfo`.
:param filename: file name of the entry
:param mtime: modified time of the entry
:param dir: if `True`, the entry is a directory
:param executable: if `True`, the entry is a executable file
:param symlink: if `True`, the entry is a symbolic link
:param comment: comment of the entry
"""
from zipfile import ZipInfo, ZIP_DEFLATED, ZIP_STORED
zipinfo = ZipInfo()
# The general purpose bit flag 11 is used to denote
# UTF-8 encoding for path and comment. Only set it for
# non-ascii files for increased portability.
# See http://www.pkware.com/documents/casestudies/APPNOTE.TXT
if any(ord(c) >= 128 for c in filename):
zipinfo.flag_bits |= 0x0800
zipinfo.filename = filename.encode('utf-8')
if mtime is not None:
mtime = to_datetime(mtime, utc)
zipinfo.date_time = mtime.utctimetuple()[:6]
# The "extended-timestamp" extra field is used for the
# modified time of the entry in unix time. It avoids
# extracting wrong modified time if non-GMT timezone.
# See http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip
# /proginfo/extra.fld
zipinfo.extra += struct.pack(
'<hhBl',
0x5455, # extended-timestamp extra block type
1 + 4, # size of this block
1, # modification time is present
to_timestamp(mtime)) # time of last modification
# external_attr is 4 bytes in size. The high order two
# bytes represent UNIX permission and file type bits,
# while the low order two contain MS-DOS FAT file
# attributes, most notably bit 4 marking directories.
if dir:
if not zipinfo.filename.endswith('/'):
zipinfo.filename += '/'
zipinfo.compress_type = ZIP_STORED
zipinfo.external_attr = 040755 << 16L # permissions drwxr-xr-x
zipinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zipinfo.compress_type = ZIP_DEFLATED
zipinfo.external_attr = 0644 << 16L # permissions -r-wr--r--
if executable:
zipinfo.external_attr |= 0755 << 16L # -rwxr-xr-x
if symlink:
zipinfo.compress_type = ZIP_STORED
zipinfo.external_attr |= 0120000 << 16L # symlink file type
if comment:
zipinfo.comment = comment.encode('utf-8')
return zipinfo
示例2: _render_zip
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
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())
示例3: add
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
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)
示例4: write_blob
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
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)
示例5: _render_zip
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
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
示例6: _render_zip
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
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())
示例7: zip_writer
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def zip_writer(dirpath, zippath):
basedir = os.path.dirname(dirpath) + os.sep
entry = ZipInfo()
entry.compress_type = compression
if os.path.isdir(dirpath):
for root, dirs, files in os.walk(dirpath):
if os.path.basename(root).startswith('.'):
# skip hidden directories
continue
dirname = root.replace(basedir, '')
for f in files:
if f[-1] == '~' or f.startswith('.'):
# skip backup files and all hidden files
continue
src = root + '/' + f
entry = ZipInfo()
entry.compress_type = compression
entry.filename = dirname + '/' + f
entry.date_time = localtime(os.path.getmtime(src))[:6]
# hacky
if dirname.startswith("html"):
if self.source == True:
entry.filename = dirname.replace('html', 'doc', 1) + "/" + f
else:
entry.filename = dirname.replace('html/', '', 1) + "/" + f
entry.filename = entry.filename.replace('html/', '', 1)
if entry.filename.startswith("examples"):
entry.filename = "tutorials/" + entry.filename
file_data = open( src, 'rb').read()
self.package.writestr(entry, file_data)
else:
# top files
entry.date_time = localtime(os.path.getmtime(dirpath))[:6]
entry.filename = os.path.basename(zippath)
file_data = open( dirpath, 'rb').read()
self.package.writestr(entry, file_data)
示例8: write_file
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def write_file (self, data, filename, description = "") :
"""Write a file into the archive
:Parameters:
- `data` (str) - data to write
- `filename` (str) - name of the file in which to store data
- `description` (str) - textual description of the data
"""
info = ZipInfo(filename)
info.comment = description
info.date_time = localtime()[:6]
info.external_attr = 0644 << 16L
info.compress_type = ZIP_DEFLATED
self._elms[filename] = (info,data)
示例9: make_dir_entry
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def make_dir_entry(name=None, date_time=None, mode=MODE_DIRECTORY):
tt = date_time.timetuple()
dir = ZipInfo()
dir.filename = name+('/' if name[-1] != '/' else '')
dir.orig_filename = dir.filename
dir.date_time = date_time.isocalendar() + (tt.tm_hour,
tt.tm_min, tt.tm_sec)
dir.compress_type = 0
dir.create_system = 0
dir.create_version = 20
dir.extract_version = 10
dir.external_attr = mode
return dir
示例10: make_file_entry
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def make_file_entry(name=None, date_time=None, mode=MODE_FILE | MODE_ARCHIVE):
tt = date_time.timetuple()
file = ZipInfo()
file.filename = name
file.orig_filename = file.filename
file.date_time = date_time.isocalendar() + (tt.tm_hour,
tt.tm_min, tt.tm_sec)
file.compress_type = 8
file.create_system = 0
file.create_version = 20
file.extract_version = 20
file.flag_bits = 2
file.external_attr = mode
return file
示例11: _zip_info
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def _zip_info(environment, name):
"""
@type environment : C{str}
@param environment : The environment name
@type name : C{str}
@param name : The name of the file
@rtype: C{ZipInfo}
@return: The Zip Info
"""
filename = "%s-%s" % (environment, name)
info = ZipInfo(filename)
info.date_time = time.localtime(time.time())[:6] #now
info.external_attr = 0666 << 16L # read-write access to everyone
info.compress_type = ZIP_DEFLATED
return info
示例12: archive_path
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def archive_path(self, path=None, report=None):
here = os.getcwd()
if path is None:
path = here
os.chdir(path)
# calculate total files and dirs first
total = 0
for root, dirs, files in os.walk('.', topdown=True):
total += 1
total += len(files)
# the tolal seems to be one greater
total -= 1
count = 1
for root, dirs, files in os.walk('.', topdown=True):
for filename in files:
fullpath = os.path.join(root, filename)
if report is not None:
report(fullpath, count, total)
self.write(fullpath)
count += 1
# do the directories last
for dirname in dirs:
fullpath = os.path.join(root, dirname)
# only add empty directories
if not os.listdir(fullpath):
fullpath = '%s/' % fullpath
info = ZipInfo(fullpath)
st = os.stat(fullpath)
mtime = time.localtime(st.st_mtime)
date_time = mtime[0:6]
info.date_time = date_time
self.writestr(info, '')
if report is not None:
report(fullpath, count, total)
count += 1
os.chdir(here)
示例13: decryptBook
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def decryptBook(userkey, inpath, outpath):
if AES is None:
raise ADEPTError(u"PyCrypto or OpenSSL must be installed.")
rsa = RSA(userkey)
with closing(ZipFile(open(inpath, 'rb'))) as inf:
namelist = set(inf.namelist())
if 'META-INF/rights.xml' not in namelist or \
'META-INF/encryption.xml' not in namelist:
print u"{0:s} is DRM-free.".format(os.path.basename(inpath))
return 1
for name in META_NAMES:
namelist.remove(name)
try:
rights = etree.fromstring(inf.read('META-INF/rights.xml'))
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
expr = './/%s' % (adept('encryptedKey'),)
bookkey = ''.join(rights.findtext(expr))
if len(bookkey) != 172:
print u"{0:s} is not a secure Adobe Adept ePub.".format(os.path.basename(inpath))
return 1
bookkey = rsa.decrypt(bookkey.decode('base64'))
# Padded as per RSAES-PKCS1-v1_5
if bookkey[-17] != '\x00':
print u"Could not decrypt {0:s}. Wrong key".format(os.path.basename(inpath))
return 2
encryption = inf.read('META-INF/encryption.xml')
decryptor = Decryptor(bookkey[-16:], encryption)
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf:
zi = ZipInfo('mimetype')
zi.compress_type=ZIP_STORED
try:
# if the mimetype is present, get its info, including time-stamp
oldzi = inf.getinfo('mimetype')
# copy across fields to be preserved
zi.date_time = oldzi.date_time
zi.comment = oldzi.comment
zi.extra = oldzi.extra
zi.internal_attr = oldzi.internal_attr
# external attributes are dependent on the create system, so copy both.
zi.external_attr = oldzi.external_attr
zi.create_system = oldzi.create_system
except:
pass
outf.writestr(zi, inf.read('mimetype'))
for path in namelist:
data = inf.read(path)
zi = ZipInfo(path)
zi.compress_type=ZIP_DEFLATED
try:
# get the file info, including time-stamp
oldzi = inf.getinfo(path)
# copy across useful fields
zi.date_time = oldzi.date_time
zi.comment = oldzi.comment
zi.extra = oldzi.extra
zi.internal_attr = oldzi.internal_attr
# external attributes are dependent on the create system, so copy both.
zi.external_attr = oldzi.external_attr
zi.create_system = oldzi.create_system
except:
pass
outf.writestr(zi, decryptor.decrypt(path, data))
except:
print u"Could not decrypt {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc())
return 2
return 0
示例14: decryptBook
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def decryptBook(keyb64, inpath, outpath):
if AES is None:
raise IGNOBLEError(u"PyCrypto or OpenSSL must be installed.")
key = keyb64.decode("base64")[:16]
aes = AES(key)
with closing(ZipFile(open(inpath, "rb"))) as inf:
namelist = set(inf.namelist())
if "META-INF/rights.xml" not in namelist or "META-INF/encryption.xml" not in namelist:
print u"{0:s} is DRM-free.".format(os.path.basename(inpath))
return 1
for name in META_NAMES:
namelist.remove(name)
try:
rights = etree.fromstring(inf.read("META-INF/rights.xml"))
adept = lambda tag: "{%s}%s" % (NSMAP["adept"], tag)
expr = ".//%s" % (adept("encryptedKey"),)
bookkey = "".join(rights.findtext(expr))
if len(bookkey) != 64:
print u"{0:s} is not a secure Barnes & Noble ePub.".format(os.path.basename(inpath))
return 1
bookkey = aes.decrypt(bookkey.decode("base64"))
bookkey = bookkey[: -ord(bookkey[-1])]
encryption = inf.read("META-INF/encryption.xml")
decryptor = Decryptor(bookkey[-16:], encryption)
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
with closing(ZipFile(open(outpath, "wb"), "w", **kwds)) as outf:
zi = ZipInfo("mimetype")
zi.compress_type = ZIP_STORED
try:
# if the mimetype is present, get its info, including time-stamp
oldzi = inf.getinfo("mimetype")
# copy across fields to be preserved
zi.date_time = oldzi.date_time
zi.comment = oldzi.comment
zi.extra = oldzi.extra
zi.internal_attr = oldzi.internal_attr
# external attributes are dependent on the create system, so copy both.
zi.external_attr = oldzi.external_attr
zi.create_system = oldzi.create_system
except:
pass
outf.writestr(zi, inf.read("mimetype"))
for path in namelist:
data = inf.read(path)
zi = ZipInfo(path)
zi.compress_type = ZIP_DEFLATED
try:
# get the file info, including time-stamp
oldzi = inf.getinfo(path)
# copy across useful fields
zi.date_time = oldzi.date_time
zi.comment = oldzi.comment
zi.extra = oldzi.extra
zi.internal_attr = oldzi.internal_attr
# external attributes are dependent on the create system, so copy both.
zi.external_attr = oldzi.external_attr
zi.create_system = oldzi.create_system
except:
pass
outf.writestr(zi, decryptor.decrypt(path, data))
except:
print u"Could not decrypt {0:s} because of an exception:\n{1:s}".format(
os.path.basename(inpath), traceback.format_exc()
)
return 2
return 0
示例15: _RealGetContents
# 需要导入模块: from zipfile import ZipInfo [as 别名]
# 或者: from zipfile.ZipInfo import date_time [as 别名]
def _RealGetContents(self):
"""Read in the table of contents for the ZIP file."""
try:
endrec = _EndRecData(self.url)
except IOError:
raise BadZipfile("File is not a zip file")
if not endrec:
raise BadZipfile, "File is not a zip file"
if self.debug > 1:
print endrec
size_cd = endrec[_ECD_SIZE] # bytes in central directory
offset_cd = endrec[_ECD_OFFSET] # offset of central directory
self.comment = endrec[_ECD_COMMENT] # archive comment
# "concat" is zero, unless zip was concatenated to another file
concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
# if endrec[_ECD_SIGNATURE] == stringEndArchive64:
# # If Zip64 extension structures are present, account for them
# concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
if self.debug > 2:
inferred = concat + offset_cd
print "given, inferred, offset", offset_cd, inferred, concat
# self.start_dir: Position of start of central directory
self.start_dir = offset_cd + concat
ECD = _http_get_partial_data(self.url, self.start_dir, self.start_dir + size_cd - 1)
data = ECD.read()
ECD.close()
fp = cStringIO.StringIO(data)
total = 0
while total < size_cd:
centdir = fp.read(sizeCentralDir)
if centdir[0:4] != stringCentralDir:
raise BadZipfile, "Bad magic number for central directory"
centdir = struct.unpack(structCentralDir, centdir)
if self.debug > 2:
print centdir
filename = fp.read(centdir[_CD_FILENAME_LENGTH])
# Create ZipInfo instance to store file information
x = ZipInfo(filename)
x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
(
x.create_version,
x.create_system,
x.extract_version,
x.reserved,
x.flag_bits,
x.compress_type,
t,
d,
x.CRC,
x.compress_size,
x.file_size,
) = centdir[1:12]
x.volume, x.internal_attr, x.external_attr = centdir[15:18]
# Convert date/time code to (year, month, day, hour, min, sec)
x._raw_time = t
x.date_time = ((d >> 9) + 1980, (d >> 5) & 0xF, d & 0x1F, t >> 11, (t >> 5) & 0x3F, (t & 0x1F) * 2)
x._decodeExtra()
x.header_offset = x.header_offset + concat
x.filename = x._decodeFilename()
self.filelist.append(x)
self.NameToInfo[x.filename] = x
# update total bytes read from central directory
total = (
total
+ sizeCentralDir
+ centdir[_CD_FILENAME_LENGTH]
+ centdir[_CD_EXTRA_FIELD_LENGTH]
+ centdir[_CD_COMMENT_LENGTH]
)
if self.debug > 2:
print "total", total