1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# COPYRIGHT NOTICE STARTS HERE
# Copyright 2019 © Samsung Electronics Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# COPYRIGHT NOTICE ENDS HERE
import argparse
import datetime
import logging
import os
import sys
import timeit
import requests
from retrying import retry
import http_file
from concurrent_downloader import ConcurrentDownloader
log = logging.getLogger(__name__)
class HttpDownloader(ConcurrentDownloader):
def __init__(self, *list_args, list_type='http_files', workers=None):
super().__init__(list_type, *list_args, workers=workers)
@property
def check_table(self):
"""
Table with information what items from lists are downloaded
"""
self.missing()
header = ['Name', 'Downloaded']
return self._check_table(header, {'Name': 'l'},
((item, item not in self._missing) for item
in self._data_list))
@staticmethod
def _make_get_request(url):
"""
Run http get request
:param url: url to reqeuest
:return: requests.Response
"""
req = requests.get(url)
req.raise_for_status()
return req
def _is_missing(self, item):
"""
Check if item is missing (not downloaded)
:param item: item to check
:return: boolean
"""
return not os.path.isfile(
'{}/{}'.format(self._data_list[item], item.rsplit('//')[-1]))
@retry(stop_max_attempt_number=5, wait_fixed=2000)
def _get_file(self, file_uri):
"""
Get http file from uri
:param file_uri: uri of the file
:return: file content
"""
if not file_uri.startswith('http'):
file_uri = 'http://' + file_uri
file_req = self._make_get_request(file_uri)
return file_req.content
def _download_item(self, item):
"""
Download http file
:param item: http file to be downloaded (tuple: (uri, dst_dir))
"""
log.info('Downloading: {}'.format(item[0]))
dst_path = '{}/{}'.format(item[1], item[0].rsplit('//')[-1])
try:
f = http_file.HttpFile(item[0], self._get_file(item[0]), dst_path)
f.save_to_file()
except Exception as err:
log.exception('Error downloading: {}: {}'.format(item[0], err))
if os.path.isfile(dst_path):
os.remove(dst_path)
raise err
log.info('Downloaded: {}'.format(f.name))
def run_cli():
"""
Run as cli tool
"""
parser = argparse.ArgumentParser(description='Download http files from list')
parser.add_argument('file_list', metavar='file-list',
help='File with list of http files to download')
parser.add_argument('--output-dir', '-o', default=os.getcwd(),
help='Destination directory for saving')
parser.add_argument('--check', '-c', action='store_true', default=False,
help='Check mode')
parser.add_argument('--debug', action='store_true', default=False,
help='Turn on debug output')
parser.add_argument('--workers', type=int, default=None,
help='Set maximum workers for parallel download (default: cores * 5)')
args = parser.parse_args()
if args.debug:
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
else:
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s')
downloader = HttpDownloader([args.file_list, args.output_dir], workers=args.workers)
if args.check:
log.info('Check mode. No download will be executed.')
log.info(downloader.check_table)
sys.exit(0)
timer_start = timeit.default_timer()
try:
downloader.download()
except RuntimeError:
sys.exit(1)
finally:
log.info('Downloading finished in {}'.format(
datetime.timedelta(seconds=timeit.default_timer() - timer_start)))
if __name__ == '__main__':
run_cli()
|