This repository has been archived on 2026-08-27. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
RequestCounter/bin/__init__.py
T

76 lines
2.0 KiB
Python
Raw Normal View History

2022-02-18 19:30:54 +08:00
#!/usr/bin/env python3
# -- coding:utf-8 --
# @Author: markushammered@gmail.com
# @Development Tool: PyCharm
# @Create Time: 2022/2/17
2022-02-18 19:36:09 +08:00
# @File Name: __init__.py
import os
2022-02-23 22:03:39 +08:00
import sys
2022-03-02 21:51:23 +08:00
from requests import get
from threading import Lock
2022-02-23 22:03:39 +08:00
from bin.utils.logger import logger
from bin.utils.settings import Settings
2022-03-02 21:51:23 +08:00
from concurrent.futures import ThreadPoolExecutor, wait
2022-02-18 19:36:09 +08:00
2022-03-02 21:51:23 +08:00
lock = Lock()
conf = Settings()
2022-02-18 19:36:09 +08:00
2022-02-23 22:03:39 +08:00
2022-03-02 21:51:23 +08:00
class Downloader:
def __init__(self, url, nums, file):
2022-02-23 22:03:39 +08:00
"""
2022-03-02 21:51:23 +08:00
初始化
:param url:
:param nums:
:param file:
2022-02-23 22:03:39 +08:00
"""
2022-03-02 21:51:23 +08:00
self.url = url
self.num = nums
self.name = file
r = get(self.url)
self.size = int(r.headers['Content-Length'])
logger.info('文件大小为:{} Mb'.format(round(self.size / 1024 / 1024, 2)))
def down(self, start, end):
2022-02-23 22:03:39 +08:00
"""
2022-03-02 21:51:23 +08:00
下载
:param start:
:param end:
2022-02-23 22:03:39 +08:00
:return:
"""
2022-03-02 21:51:23 +08:00
headers = {'Range': 'bytes={}-{}'.format(start, end)}
r = get(self.url, headers=headers, stream=True)
lock.acquire()
with open(self.name, "rb+") as fp:
fp.seek(start)
fp.write(r.content)
lock.release()
2022-02-23 22:03:39 +08:00
2022-03-02 21:51:23 +08:00
def run(self):
2022-02-23 22:03:39 +08:00
"""
2022-03-02 21:51:23 +08:00
运行
2022-02-23 22:03:39 +08:00
:return:
"""
2022-03-02 21:51:23 +08:00
fp = open(self.name, "wb")
fp.truncate(self.size)
fp.close()
part = self.size // self.num
pool = ThreadPoolExecutor(max_workers=self.num)
futures = []
for i in range(self.num):
start = part * i
if i == self.num - 1:
end = self.size
else:
end = start + part - 1
futures.append(pool.submit(self.down, start, end))
wait(futures)
logger.info('数据库: %s 下载完成' % self.name.split('/')[-1])
2022-02-23 22:03:39 +08:00
if __name__ != '__main__':
2022-03-02 21:51:23 +08:00
if not os.path.exists('./bin/db/data.db'):
logger.error('没有检测到数据库文件, 即将开始下载data.db')
Downloader('https://themedatabase.vercel.app/assets', 4, './bin/db/data.db').run()