def test_filesize(self): for test, expect in ( (1, u'1.00 B'), (1024, u'1.00 kB'), (1448576, u'1.38 MB'), ): result = size.filesize(test) assert result == expect, '%r <> %r' % (result, expect)
def size(filename, format='decimal'): ''' Retrieve the size of a file. :param filename: name of the file ''' if isinstance(filename, file): filename = filename.name return filesize(os.stat(filename)[stat.ST_SIZE], format)
def __init__(self, data): if isinstance(data, str): # Backwards compatibility self.filename = data.rsplit('/', 1)[1] self.url = data self.is_image = True self.size = 0 else: self.filename = data['filename'] self.url = data['url'] self.is_image = data['is_image'] self.size = filesize(data['size']) self.width = data.get('width') self.height = data.get('height')
def to_representation(self, instance): ret = super().to_representation(instance) if any([ ret['height'], ret['width'], ret['filename'].rsplit('.', 1)[-1] in ['png', 'jpg', 'jpeg', 'gif', 'webm', 'webp', 'mp4'], re.match( r'data:(?:image/(?P<mimetype>\w+))?(?:;(?P<b64>base64))?,(?P<data>(?:[A-Za-z0-9+/]{4})' r'``*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?)', ret['url']) ]): ret['is_image'] = True ret['size'] = filesize(ret['size']) return ret
def to_representation(self, instance): ret = super().to_representation(instance) ext = ret.get('filename').rsplit('.', 1)[-1].lower() if ext in ['png', 'jpg', 'jpeg', 'webp']: ret['type'] = 'image' elif ext in 'gifv': ret['type'] = 'gif' elif ext in ['mp4', 'webm']: ret['type'] = 'video' if ret.get('height') is not None or ret.get('width') is not None: ret['height'], ret['width'] = scale_image(ret['height'], ret['width'], 300, 400) ret['size'] = filesize(ret['size'] or 0) return ret
def size(filename, format='decimal'): ''' Retrieve the size of a file. :param filename: name of the file >>> size('/etc/mime.types') # doctest: +SKIP 23.70 kB ''' if isinstance(filename, file): filename = filename.name return filesize(os.stat(filename)[stat.ST_SIZE], format)