1
2
3
4
5
6
7
8 """
9 This module implements the SmartIO class
10 """
11
12 import os
13 try:
14 from cStringIO import StringIO
15 except ImportError:
16 from io import BytesIO as StringIO
17
19 """
20 The SmartIO class allows one to put a cap on the memory consumption.
21 StringIO objects are very fast, because they are stored in memory, but
22 if they are too big the memory footprint becomes noticeable.
23 The write method of a SmartIO determines if the data that is to be added
24 to the (initially) StrintIO object does not exceed a certain threshold; if
25 it does, it switches the storage to a temporary disk file
26 """
27 - def __init__(self, max_mem_size=16384, force_mem=0):
28 self._max_mem_size = max_mem_size
29 self._io = StringIO()
30
31
32
33
34 if force_mem:
35 self._fixed = 1
36 else:
37 self._fixed = 0
38
40 self._max_mem_size = max_mem_size
41
43 return self._max_mem_size
44
46 if not self._fixed:
47
48 if len(data) + self._io.tell() > self._max_mem_size:
49
50 tmpfile = _tempfile()
51 tmpfile.write(self._io.getvalue())
52 self._fixed = 1
53 self._io = tmpfile
54
55 self._io.write(data)
56
58 return getattr(self._io, name)
59
60
62 import tempfile
63 (fd, fname) = tempfile.mkstemp(prefix="_rhn_transports-%d-" \
64 % os.getpid())
65
66 os.unlink(fname)
67 return os.fdopen(fd, "wb+")
68