Skip to content

Commit e12c5b9

Browse files
committed
Allow the user to control the download
Allows the caller of the 'download' method to get the response object back to download the item as needed. This allows the caller to iteratively download in whatever chunk size is desired, to download to whatever location is desired, etc.
1 parent cdc333f commit e12c5b9

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

smartfile/__init__.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,10 @@ def _do_request(self, request, url, **kwargs):
6767
return response.text
6868
else:
6969
# This might be a file, so return it.
70-
return response.raw
70+
if kwargs.get('params', {}).get('raw', True):
71+
return response.raw
72+
else:
73+
return response
7174

7275
def _request(self, method, endpoint, id=None, **kwargs):
7376
"Handles retrying failed requests and error handling."
@@ -145,14 +148,19 @@ def upload(self, filename, fileobj):
145148
arg = (filename, fileobj)
146149
return self.post('/path/data/', file=arg)
147150

148-
def download(self, file_to_be_downloaded):
151+
def download(self, file_to_be_downloaded, perform_download=True):
149152
""" file_to_be_downloaded is a file-like object that has already
150153
been uploaded, you cannot download folders """
154+
response = self.get(
155+
'/path/data/', file_to_be_downloaded, raw=False)
156+
if not perform_download:
157+
# The caller can decide how to process the download of the data
158+
return response
159+
151160
# download uses shutil.copyfileobj to download, which copies
152161
# the data in chunks
153162
o = open(file_to_be_downloaded, 'wb')
154-
return shutil.copyfileobj(self.get('/path/data/',
155-
file_to_be_downloaded), o)
163+
return shutil.copyfileobj(response.raw, o)
156164

157165
def move(self, src_path, dst_path):
158166
# check destination folder for / at end

test/test_smartfile.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import absolute_import
22

33
import os
4+
import requests
45
import unittest
56

67
try:
@@ -47,6 +48,8 @@ def upload(self):
4748
self.assertEquals(self.get_data()['size'], f.tell())
4849

4950
def download(self):
51+
response = self.api.download(TESTFN, False)
52+
self.assertTrue(isinstance(response, requests.Response))
5053
self.api.download(TESTFN)
5154
self.assertEquals(self.get_data()['size'], os.path.getsize(TESTFN))
5255

0 commit comments

Comments
 (0)