forked from twisted/treq
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
update download_file to make use of collect flow control
- Loading branch information
Showing
1 changed file
with
24 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,31 @@ | ||
import io | ||
import functools | ||
|
||
from twisted.internet.task import react | ||
from twisted.internet import threads, defer | ||
|
||
import treq | ||
|
||
|
||
def download_file(reactor, url, destination_filename): | ||
destination = open(destination_filename, 'wb') | ||
d = treq.get(url, unbuffered=True) | ||
d.addCallback(treq.collect, destination.write) | ||
d.addBoth(lambda _: destination.close()) | ||
return d | ||
def deferToThread(reactor, f, *args, **kwargs): | ||
if reactor is None: | ||
from twisted.internet import reactor | ||
return threads.deferToThreadPool( | ||
reactor, reactor.getThreadPool(), | ||
f, *args, **kwargs | ||
) | ||
|
||
|
||
@defer.inlineCallbacks | ||
def download_file(reactor, url, dest): | ||
response = yield treq.get(url, reactor=reactor, unbuffered=True) | ||
f = yield deferToThread(reactor, io.open, dest, 'wb') | ||
try: | ||
yield treq.collect( | ||
response, | ||
functools.partial(deferToThread, reactor, f.write), | ||
) | ||
finally: | ||
yield deferToThread(reactor, f.close) | ||
|
||
react(download_file, ['http://httpbin.org/get', 'download.txt']) |