source: trunk/src/allmydata/util/consumer.py

Last change on this file was 1cfe843d, checked in by Alexandre Detiste <alexandre.detiste@…>, at 2024-02-22T23:40:25Z

more python2 removal

  • Property mode set to 100644
File size: 1.0 KB
Line 
1"""
2This file defines a basic download-to-memory consumer, suitable for use in
3a filenode's read() method. See download_to_data() for an example of its use.
4
5Ported to Python 3.
6"""
7
8from zope.interface import implementer
9from twisted.internet.interfaces import IConsumer
10
11
12@implementer(IConsumer)
13class MemoryConsumer(object):
14
15    def __init__(self):
16        self.chunks = []
17        self.done = False
18
19    def registerProducer(self, p, streaming):
20        self.producer = p
21        if streaming:
22            # call resumeProducing once to start things off
23            p.resumeProducing()
24        else:
25            while not self.done:
26                p.resumeProducing()
27
28    def write(self, data):
29        self.chunks.append(data)
30
31    def unregisterProducer(self):
32        self.done = True
33
34
35def download_to_data(n, offset=0, size=None):
36    """
37    Return Deferred that fires with results of reading from the given filenode.
38    """
39    d = n.read(MemoryConsumer(), offset, size)
40    d.addCallback(lambda mc: b"".join(mc.chunks))
41    return d
Note: See TracBrowser for help on using the repository browser.