def serve(self, request, path):
# the following code is largely borrowed from `django.views.static.serve`
# and django-filetransfers: filetransfers.backends.default
fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path)
if not os.path.exists(fullpath):
raise Http404('"{0}" does not exist'.format(fullpath))
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
content_type = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
return HttpResponseNotModified(content_type=content_type)
response = HttpResponse(open(fullpath, 'rb').read(), content_type=content_type)
response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
# filename = os.path.basename(path)
# response['Content-Disposition'] = smart_str(u'attachment; filename={0}'.format(filename))
return response
python类ST_SIZE的实例源码
def walker(arg, dirname, fnames):
d = os.getcwd()
os.chdir(dirname)
try:
fnames.remove('Thumbs')
except ValueError:
pass
for f in fnames:
if not os.path.isfile(f):
continue
size = os.stat(f)[stat.ST_SIZE]
if size < 100:
continue
if filesBySize.has_key(size):
a = filesBySize[size]
else:
a = []
filesBySize[size] = a
a.append(os.path.join(dirname, f))
os.chdir(d)
def get_last_offset(self, f):
st = os.fstat(f.fileno())
ino = st[stat.ST_INO]
size = st[stat.ST_SIZE]
try:
last = self.read_last_stat()
except IOError:
# no such file
last = {'inode': 0, 'offset': 0}
if last['inode'] == ino and last['offset'] <= size:
return last['offset']
else:
return 0
def readData(self, filename, file_index):
# Open file and read file size
self.warning("Load input file: %s" % filename)
data = open(filename, 'rb')
orig_filesize = fstat(data.fileno())[ST_SIZE]
if not orig_filesize:
raise ValueError("Input file (%s) is empty!" % filename)
# Read bytes
if self.max_size:
data = data.read(self.max_size)
else:
data = data.read()
# Display message if input is truncated
if len(data) < orig_filesize:
percent = len(data) * 100.0 / orig_filesize
self.warning("Truncate file to %s bytes (%.2f%% of %s bytes)" \
% (len(data), percent, orig_filesize))
# Convert to Python array object
return array('B', data)
def multipart_encode(vars, files, boundary = None, buffer = None):
if boundary is None:
boundary = mimetools.choose_boundary()
if buffer is None:
buffer = ''
for(key, value) in vars:
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"' % key
buffer += '\r\n\r\n' + value + '\r\n'
for(key, fd) in files:
file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
filename = fd.name.split('/')[-1]
contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
buffer += 'Content-Type: %s\r\n' % contenttype
# buffer += 'Content-Length: %s\r\n' % file_size
fd.seek(0)
buffer += '\r\n' + fd.read() + '\r\n'
buffer += '--%s--\r\n\r\n' % boundary
return boundary, buffer
def serve(self, request, file_obj, **kwargs):
fullpath = file_obj.path
# the following code is largely borrowed from `django.views.static.serve`
# and django-filetransfers: filetransfers.backends.default
if not os.path.exists(fullpath):
raise Http404('"%s" does not exist' % fullpath)
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
content_type_key = 'mimetype' if LTE_DJANGO_1_4 else 'content_type'
response_params = {content_type_key: self.get_mimetype(fullpath)}
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
return HttpResponseNotModified(**response_params)
response = HttpResponse(open(fullpath, 'rb').read(), **response_params)
response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs)
return response
def test_files(self):
"""
Test reading and writing of files via rand functions.
"""
# Write random bytes to a file
tmpfile = self.mktemp()
# Make sure it exists (so cleanup definitely succeeds)
fObj = file(tmpfile, 'w')
fObj.close()
try:
rand.write_file(tmpfile)
# Verify length of written file
size = os.stat(tmpfile)[stat.ST_SIZE]
self.assertEquals(size, 1024)
# Read random bytes from file
rand.load_file(tmpfile)
rand.load_file(tmpfile, 4) # specify a length
finally:
# Cleanup
os.unlink(tmpfile)
def GetItemData(self, colid, colData):
fmt_id, pid = colid
fmt_id==self._reg_clsid_
flags, attr, reserved, ext, name = colData
if ext.lower() not in [".py", ".pyw"]:
return None
if pid==0:
ext = ".pyc"
else:
ext = ".pyo"
check_file = os.path.splitext(name)[0] + ext
try:
st = os.stat(check_file)
return st[stat.ST_SIZE]
except OSError:
# No file
return None
def gen_folder_listing(path):
l = os.listdir(path)
s = '<?xml version="1.0"?>\n<folder-listing>\n'
for i in l:
objpath = os.path.join(path, i)
if os.path.isdir(objpath):
args = (i, unix2bluetime(os.stat(objpath)[stat.ST_CTIME]))
s += ' <folder name="%s" created="%s" />' % args
else:
args = (i, unix2bluetime(os.stat(objpath)[stat.ST_CTIME]),
os.stat(objpath)[stat.ST_SIZE])
s += ' <file name="%s" created="%s" size="%s" />' % args
s += "</folder-listing>\n"
if sys.version_info.major < 3:
s = unicode(s)
return s
def copy_file_if_modified(src_path, dest_path):
"""Only copies the file from the source path to the destination path if it doesn't exist yet or it has
been modified. Intended to provide something of an optimisation when a project has large trees of assets."""
# if the destination path is a directory, delete it completely - we assume here we are
# writing a file to the filesystem
if os.path.isdir(dest_path):
shutil.rmtree(dest_path)
must_copy = False
if not os.path.exists(dest_path):
must_copy = True
else:
src_stat = os.stat(src_path)
dest_stat = os.stat(dest_path)
# if the size or last modified timestamp are different
if ((src_stat[stat.ST_SIZE] != dest_stat[stat.ST_SIZE]) or
(src_stat[stat.ST_MTIME] != dest_stat[stat.ST_MTIME])):
must_copy = True
if must_copy:
shutil.copy2(src_path, dest_path)
def test_files(self):
"""
Test reading and writing of files via rand functions.
"""
# Write random bytes to a file
tmpfile = self.mktemp()
# Make sure it exists (so cleanup definitely succeeds)
fObj = file(tmpfile, 'w')
fObj.close()
try:
rand.write_file(tmpfile)
# Verify length of written file
size = os.stat(tmpfile)[stat.ST_SIZE]
self.assertEquals(size, 1024)
# Read random bytes from file
rand.load_file(tmpfile)
rand.load_file(tmpfile, 4) # specify a length
finally:
# Cleanup
os.unlink(tmpfile)
def setUp(self):
if os.path.exists(TESTFN):
mode = 'r+b'
else:
mode = 'w+b'
with self.open(TESTFN, mode) as f:
current_size = os.fstat(f.fileno())[stat.ST_SIZE]
if current_size == size+1:
return
if current_size == 0:
f.write(b'z')
f.seek(0)
f.seek(size)
f.write(b'a')
f.flush()
self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
def _read_write_test(self, path):
"""
Verify that ``rand.write_file`` and ``rand.load_file`` can be used.
"""
# Create the file so cleanup is more straightforward
with open(path, "w"):
pass
try:
# Write random bytes to a file
rand.write_file(path)
# Verify length of written file
size = os.stat(path)[stat.ST_SIZE]
self.assertEqual(1024, size)
# Read random bytes from file
rand.load_file(path)
rand.load_file(path, 4) # specify a length
finally:
# Cleanup
os.unlink(path)
def GetItemData(self, colid, colData):
fmt_id, pid = colid
fmt_id==self._reg_clsid_
flags, attr, reserved, ext, name = colData
if ext.lower() not in [".py", ".pyw"]:
return None
if pid==0:
ext = ".pyc"
else:
ext = ".pyo"
check_file = os.path.splitext(name)[0] + ext
try:
st = os.stat(check_file)
return st[stat.ST_SIZE]
except OSError:
# No file
return None
def CheckLoaderModule(dll_name):
suffix = ""
if is_debug_build: suffix = "_d"
template = os.path.join(this_dir,
"PyISAPI_loader" + suffix + ".dll")
if not os.path.isfile(template):
raise ConfigurationError(
"Template loader '%s' does not exist" % (template,))
# We can't do a simple "is newer" check, as the DLL is specific to the
# Python version. So we check the date-time and size are identical,
# and skip the copy in that case.
src_stat = os.stat(template)
try:
dest_stat = os.stat(dll_name)
except os.error:
same = 0
else:
same = src_stat[stat.ST_SIZE]==dest_stat[stat.ST_SIZE] and \
src_stat[stat.ST_MTIME]==dest_stat[stat.ST_MTIME]
if not same:
log(2, "Updating %s->%s" % (template, dll_name))
shutil.copyfile(template, dll_name)
shutil.copystat(template, dll_name)
else:
log(2, "%s is up to date." % (dll_name,))
def walker(arg, dirname, fnames):
d = os.getcwd()
os.chdir(dirname)
global filesBySize
try:
fnames.remove('Thumbs')
except ValueError:
pass
for f in fnames:
if not os.path.isfile(f):
continue
size = os.stat(f)[stat.ST_SIZE]
#print f + " size: " + str(size)
if size < 100:
continue
if filesBySize.has_key(size):
a = filesBySize[size]
else:
a = []
filesBySize[size] = a
a.append(os.path.join(dirname, f))
os.chdir(d)
def GetItemData(self, colid, colData):
fmt_id, pid = colid
fmt_id==self._reg_clsid_
flags, attr, reserved, ext, name = colData
if ext.lower() not in [".py", ".pyw"]:
return None
if pid==0:
ext = ".pyc"
else:
ext = ".pyo"
check_file = os.path.splitext(name)[0] + ext
try:
st = os.stat(check_file)
return st[stat.ST_SIZE]
except OSError:
# No file
return None
def CheckLoaderModule(dll_name):
suffix = ""
if is_debug_build: suffix = "_d"
template = os.path.join(this_dir,
"PyISAPI_loader" + suffix + ".dll")
if not os.path.isfile(template):
raise ConfigurationError(
"Template loader '%s' does not exist" % (template,))
# We can't do a simple "is newer" check, as the DLL is specific to the
# Python version. So we check the date-time and size are identical,
# and skip the copy in that case.
src_stat = os.stat(template)
try:
dest_stat = os.stat(dll_name)
except os.error:
same = 0
else:
same = src_stat[stat.ST_SIZE]==dest_stat[stat.ST_SIZE] and \
src_stat[stat.ST_MTIME]==dest_stat[stat.ST_MTIME]
if not same:
log(2, "Updating %s->%s" % (template, dll_name))
shutil.copyfile(template, dll_name)
shutil.copystat(template, dll_name)
else:
log(2, "%s is up to date." % (dll_name,))
def serve(self, request, file_obj, **kwargs):
fullpath = file_obj.path
# the following code is largely borrowed from `django.views.static.serve`
# and django-filetransfers: filetransfers.backends.default
if not os.path.exists(fullpath):
raise Http404('"%s" does not exist' % fullpath)
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
content_type_key = 'mimetype' if LTE_DJANGO_1_4 else 'content_type'
response_params = {content_type_key: self.get_mimetype(fullpath)}
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
return HttpResponseNotModified(**response_params)
response = HttpResponse(open(fullpath, 'rb').read(), **response_params)
response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs)
return response
def setUp(self):
if os.path.exists(TESTFN):
mode = 'r+b'
else:
mode = 'w+b'
with self.open(TESTFN, mode) as f:
current_size = os.fstat(f.fileno())[stat.ST_SIZE]
if current_size == size+1:
return
if current_size == 0:
f.write(b'z')
f.seek(0)
f.seek(size)
f.write(b'a')
f.flush()
self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
def setUp(self):
if os.path.exists(TESTFN):
mode = 'r+b'
else:
mode = 'w+b'
with self.open(TESTFN, mode) as f:
current_size = os.fstat(f.fileno())[stat.ST_SIZE]
if current_size == size+1:
return
if current_size == 0:
f.write(b'z')
f.seek(0)
f.seek(size)
f.write(b'a')
f.flush()
self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
def _read_write_test(self, path):
"""
Verify that ``rand.write_file`` and ``rand.load_file`` can be used.
"""
# Create the file so cleanup is more straightforward
with open(path, "w"):
pass
try:
# Write random bytes to a file
rand.write_file(path)
# Verify length of written file
size = os.stat(path)[stat.ST_SIZE]
self.assertEqual(1024, size)
# Read random bytes from file
rand.load_file(path)
rand.load_file(path, 4) # specify a length
finally:
# Cleanup
os.unlink(path)
def test_files(self):
"""
Test reading and writing of files via rand functions.
"""
# Write random bytes to a file
tmpfile = self.mktemp()
# Make sure it exists (so cleanup definitely succeeds)
fObj = open(tmpfile, 'w')
fObj.close()
try:
rand.write_file(tmpfile)
# Verify length of written file
size = os.stat(tmpfile)[stat.ST_SIZE]
self.assertEquals(size, 1024)
# Read random bytes from file
rand.load_file(tmpfile)
rand.load_file(tmpfile, 4) # specify a length
finally:
# Cleanup
os.unlink(tmpfile)
def updateDisplay(self, file_list):
""""""
for path in file_list:
file_stats = os.stat(path)
creation_time = time.strftime(
"%m/%d/%Y %I:%M %p",
time.localtime(file_stats[stat.ST_CTIME]))
modified_time = time.strftime(
"%m/%d/%Y %I:%M %p",
time.localtime(file_stats[stat.ST_MTIME]))
file_size = file_stats[stat.ST_SIZE]
if file_size > 1024:
file_size = file_size / 1024.0
file_size = "%.2f KB" % file_size
self.file_list.append(FileInfo(path,
creation_time,
modified_time,
file_size))
self.olv.SetObjects(self.file_list)
def generateOVF( name, osname, osid, diskname, disksize, mem=1024, cpus=1,
vmname='Mininet-VM', vminfo='A Mininet Virtual Machine' ):
"""Generate (and return) OVF file "name.ovf"
name: root name of OVF file to generate
osname: OS name for OVF (Ubuntu | Ubuntu 64-bit)
osid: OS ID for OVF (93 | 94 )
diskname: name of disk file
disksize: size of virtual disk in bytes
mem: VM memory size in MB
cpus: # of virtual CPUs
vmname: Name for VM (default name when importing)
vmimfo: Brief description of VM for OVF"""
ovf = name + '.ovf'
filesize = stat( diskname )[ ST_SIZE ]
params = dict( osname=osname, osid=osid, diskname=diskname,
filesize=filesize, disksize=disksize, name=name,
mem=mem, cpus=cpus, vmname=vmname, vminfo=vminfo )
xmltext = OVFTemplate % params
with open( ovf, 'w+' ) as f:
f.write( xmltext )
return ovf
def get_st_size(file_path):
if type(file_path) == list:
total_size = 0
for fl in file_path:
if os.path.exists(fl):
total_size += os.stat(fl)[ST_SIZE]
return total_size
else:
return os.stat(file_path)[ST_SIZE]
def get_content_size(self):
"""Retrieve the total size of the resource at the given path.
This method may be overridden by subclasses.
.. versionadded:: 3.1
.. versionchanged:: 4.0
This method is now always called, instead of only when
partial results are requested.
"""
stat_result = self._stat()
return stat_result[stat.ST_SIZE]
def get_content_size(self):
"""Retrieve the total size of the resource at the given path.
This method may be overridden by subclasses.
.. versionadded:: 3.1
.. versionchanged:: 4.0
This method is now always called, instead of only when
partial results are requested.
"""
stat_result = self._stat()
return stat_result[stat.ST_SIZE]
def get_content_size(self):
"""Retrieve the total size of the resource at the given path.
This method may be overridden by subclasses.
.. versionadded:: 3.1
.. versionchanged:: 4.0
This method is now always called, instead of only when
partial results are requested.
"""
stat_result = self._stat()
return stat_result[stat.ST_SIZE]
def _file_size(f):
st = os.fstat(f.fileno())
return st[stat.ST_SIZE]