def __init__(self, data=None, fp=None, length=-1): assert bool(data is not None) ^ bool(fp) if length == -1: if data is not None: length = len(data) else: length = get_size(fp) # can be -1 # We allow writer reuse, but if we're working with a stream, we cannot # seek. Copy the data to a tempfile. if fp and not can_seek(fp): newfp = SpooledTemporaryFile(MAX_INMEMORY_SIZE) sendfile(newfp, fp) length = newfp.tell() newfp.seek(0) fp = newfp self.data = data self.fp = fp self.fpreads = 0 # keep track of fp usage self.length = length assert length >= 0 self.use_tempfile = length > MAX_INMEMORY_SIZE
def _encrypt_with_none(self): if self.fp: # Return a new file so they're not closing ours. try: fileno = self.fp.fileno() except UnsupportedOperation: newfp = SpooledTemporaryFile(MAX_INMEMORY_SIZE) sendfile(newfp, self.fp) newfp.seek(0) return newfp else: return fdopen(fileno, "rb") else: # For no encryption, passing around a BytesIO is no extra effort if # the data already was a string. return BytesIO(self.data)