Line | |
---|
1 | """ |
---|
2 | This file defines a basic download-to-memory consumer, suitable for use in |
---|
3 | a filenode's read() method. See download_to_data() for an example of its use. |
---|
4 | |
---|
5 | Ported to Python 3. |
---|
6 | """ |
---|
7 | |
---|
8 | from zope.interface import implementer |
---|
9 | from twisted.internet.interfaces import IConsumer |
---|
10 | |
---|
11 | |
---|
12 | @implementer(IConsumer) |
---|
13 | class 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 | |
---|
35 | def 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.