download_speed/downloader.py

33 lines
1.1 KiB
Python
Raw Normal View History

2019-06-16 16:42:44 +08:00
import requests
import datetime
2019-06-16 18:28:19 +08:00
import model
2019-06-16 16:42:44 +08:00
# file_size if byte
# longest_time seconds
2019-06-16 16:42:44 +08:00
def download_file(
servers, chunk_size=4 * 1024, file_size=100 * 1024 * 1024, longest_time=60
):
2019-06-16 18:28:19 +08:00
for server in servers:
url = server["url"]
server_name = server["name"]
chunk_read = 0
s_time = datetime.datetime.now()
with requests.get(url, stream=True) as r:
for chunk in r.iter_content(chunk_size):
if chunk:
chunk_read += len(chunk)
e_time = datetime.datetime.now()
duration = (e_time - s_time).total_seconds()
if chunk_read >= file_size:
break
if duration >= longest_time:
print('Longer than {longest_time} seconds. Stopped.'.format(longest_time=longest_time))
break
2019-06-16 18:28:19 +08:00
speed = chunk_read / duration / 1024 / 1024 * 8 # mega bit
model.add_record(server_name, speed)
# print(now_timestamp{} MB download".format(chunk_read / 1024 / 1024))
# print("{} seconds".format(duration / 1))
return speed