Menu

[r31]: / python_webdav / file_wrapper.py  Maximize  Restore  History

Download this file

53 lines (41 with data), 1.8 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
class FileWrapper(file):
def __init__(self, *args, **kwargs):
""" :param force_size: Sets a size to force the file to be read
in this sized blocks. httplib will send files
in 8192 chunks if force_size is not set.
:type force_size: int
:param callback: function to call when a percentage step is reached
:type callback: function
:param callback_size: Step (in percentage) at which callback should
be called. This must be larger than 0.
:type callback_size: int
TODO: finish implementing callback ability (not tested)
"""
file.__init__(self, *args, **kwargs)
# Get options
self.force_size = getattr(self, 'force_size', False)
self.callback = getattr(self, 'callback', None)
self.callback_percent = getattr(self, 'callback_size', 100)
# Avoid Zero division errors
if self.callback_percent == 0:
self.callback_percent = 1
# This next line may be redundant
self.initial_read_pos = self.tell()
self.file_size = os.path.getsize(self.name)
def read(self, size=-1):
""" Just like a file objects read method but will "rewind" after the
file has reached EOF.
"""
if self.force_size:
size = self.force_size
data = file.read(self, size)
if not data or size < 0 or size >= self.file_size:
self.seek(self.initial_read_pos)
try:
percent = int((float(size) / self.file_size) * 100)
except ZeroDivisionError, err:
percent = 0
if self.callback and percent % self.callback_percent == 0:
self.callback()
return data