|
6 | 6 | APIException, |
7 | 7 | DataFileTimeout, |
8 | 8 | JobNotProcessing) |
9 | | -from ravenpackapi.util import to_curl, parse_csv_line |
| 9 | +from ravenpackapi.util import parse_csv_line |
| 10 | +from ravenpackapi.utils.file_saving import save_stream_response |
10 | 11 |
|
11 | 12 | logger = logging.getLogger(__name__) |
12 | 13 |
|
@@ -104,26 +105,16 @@ def wait_for_completion(self, timeout_seconds=None): |
104 | 105 | def save_to_file(self, filename): |
105 | 106 | api = self.api |
106 | 107 | job = self # just to be clear |
107 | | - with open(filename, 'wb') as output: |
108 | | - job.wait_for_completion() |
109 | | - logger.info(u"Writing to %s" % filename) |
110 | | - |
111 | | - # this is a different request than the normal API |
112 | | - # streaming the file in chunks |
113 | | - response = api.session.get(job.url, |
114 | | - headers=api.headers, |
115 | | - stream=True, |
116 | | - **api.common_request_params |
117 | | - ) |
118 | | - if response.status_code != 200: |
119 | | - logger.error("Error calling the API, we tried: %s" % to_curl(response.request)) |
120 | | - raise APIException( |
121 | | - 'Got an error {status}: body was \'{error_message}\''.format( |
122 | | - status=response.status_code, error_message=response.text |
123 | | - ), response=response) |
124 | | - for chunk in response.iter_content(chunk_size=self._CHUNK_SIZE): |
125 | | - if chunk: |
126 | | - output.write(chunk) |
| 108 | + job.wait_for_completion() |
| 109 | + |
| 110 | + # this is a different request than the normal API |
| 111 | + # streaming the file in chunks |
| 112 | + response = api.session.get(job.url, |
| 113 | + headers=api.headers, |
| 114 | + stream=True, |
| 115 | + **api.common_request_params |
| 116 | + ) |
| 117 | + save_stream_response(response, filename, chunk_size=self._CHUNK_SIZE) |
127 | 118 |
|
128 | 119 | @api_method |
129 | 120 | def iterate_results(self, include_headers=False): |
|
0 commit comments