首页 > 编程语言 >Python fir 单线程下载脚本

Python fir 单线程下载脚本

时间:2023-02-03 00:23:45浏览次数:47  
标签:fir Python self url 单线程 version build print size


import requests,os,time
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from pathlib import Path
from tqdm import tqdm
from threading import Thread
from time import time

downloadPath =Path.cwd().parent.parent.parent.joinpath("apk","download")


def Interrupt_exception(func):
    '''
    定义一个装饰器:
    捕捉手动停止错误
    '''

    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
            return result
        except KeyboardInterrupt:
            print("手动停止")
            os._exit(0)

    return wrapper

class myloadApk():

    def __init__(self,which,version=None,bulid=None,changelog="Inner"):
        self.which = which
        self.version = version
        self.build = bulid
        self.changelog = changelog
        self.thread_num = 3
        self.url = None


    @Interrupt_exception
    def findApk(self):
        '''
        查找下载APP id
        '''
        for i in range(1,10):
            print("正在查询第" +str(i)+"页")
            url = "http://fir-api.fircli.cn/apps/" + self.id + "/releases?api_token=" + self.api_token + "&page="+str(i)
            respones = requests.get(url, verify=False)
            allHistory = respones.json()['datas']
            for build_version in allHistory:
                print(build_version["version"])
                print(build_version["build"])
                print(build_version["changelog"])
                print(build_version["id"])
                print("--------********---------")
                if (self.version == None or build_version["version"] == self.version) and (self.build == None or build_version["build"] == self.build) and self.changelog in build_version["changelog"]:
                    self.version = build_version["version"]
                    self.build = build_version["build"]
                    return build_version["id"]

    def download_token(self):
        '''
        获取download_token
        '''
        url ="http://api.bq04.com/apps/"+self.id+"/download_token?api_token="+self.api_token
        respones = requests.get(url, verify=False)
        return respones.json()['download_token']

    def bytes_format(self, value):
        '''
        文件大小自转换
        '''
        units = ["B", "KB", "MB", "GB", "TB", "PB"]
        size = 1024.0
        for i in range(len(units)):
            if (value / size) < 1:
                return "%.2f%s" % (value, units[i])
            value = value / size

    def get_url(self):
        '''
        获取下载url
        '''
        down_token = self.download_token()
        releaseid = self.findApk()
        print("%s : %s(%s) %s" % (self.which, self.version, self.build, self.changelog))
        url = "http://download.bq04.com/apps/"+self.id+"/install?download_token="+down_token+"&release_id="+releaseid
        return url

    def get_total_size(self):
        '''
        获取下载文件大小
        '''
        Response = requests.get(self.url, stream=True, verify=False)
        # 总大小
        total_size = int(Response.headers.get('content-length', 0))
        print(self.bytes_format(total_size))
        return total_size

    @Interrupt_exception
    def loadAPK(self):
        '''
        单线程下载ing
        '''
        start = time()
        self.url = self.get_url()
        self.total_size = self.get_total_size()
        paths = str(downloadPath) + "/HelloTalk_" + self.version + "_" + self.build + "_" + self.which + ".apk"
        # stream=True的作用是仅让响应头被下载,连接保持打开状态,
        if Path(paths).exists():
            temp_size = os.path.getsize(paths)
            print("已下载文件 "+ self.bytes_format(temp_size))
        else: temp_size = 0
        if temp_size >= self.total_size:
            print("下载完成")
            return paths
        header = {"Range": f"bytes={temp_size}-{self.total_size}"}
        Req = requests.get(self.url, headers=header, stream=True, verify=False, timeout=10)
        with open(paths, "ab") as file, tqdm(
            initial=temp_size,
            desc="正在下载",
            total=self.total_size,
            unit='',
            unit_scale=True,
            unit_divisor=1024,
        ) as bar:
            for data in Req.iter_content(chunk_size=1024):  # 边下载边存硬盘
                size = file.write(data)
                bar.update(size)
        end = time()
        print('总共耗费了%.2f秒.' % (end - start))
        return paths

    @Interrupt_exception
    def adb_install(self):
        '''
        安装ing
        '''
        file_names = self.loadAPK()
        print("正在安装...")
        cmd_shell = "adb -d install -r -d " + file_names
        openApp = os.system(cmd_shell)
        if openApp == 0:
            os.system("adb -d shell am start -n com.hellotalk/.lib.main.launch.ui.LaunchActivity")


标签:fir,Python,self,url,单线程,version,build,print,size
From: https://www.cnblogs.com/QingshanY/p/17087815.html

相关文章

  • Python 高级编程之面向对象(一)
    目录一、概述二、面向对象的概念介绍1)类定义2)类属性3)类方法4)构造方法(init)三、面向对象封装、继承和多态1)封装2)继承3)子类重新方法和super()调用父类方法4)多态一、概述科班......
  • Python fir 下载脚本兼容iOS
    思路方法一:类似Android处理,用接口下载文件后,直接通过数据线进行安装方法二:通过服务端返回下载URL,iOS用快捷指令处理 最后选取的第二种方法。对之前脚本做如下修改:1......
  • python内置函数map
    map()函数介绍map()是python的一个内置函数,其作用是返回一个迭代器,该迭代器将function函数应用于iterable的每个项,并产生结果。map函数的语法:map(function,iterable,......
  • Jupyter IPython Anaconda
    IPythonNotebook改名叫JupyterNotebook了。ref:​​​windows中jupyter(原ipythonnotebook)中文件工作路径的设置​​Anaconda是专注于数据分析的Python发行版本,包含......
  • 用Python连接IBM量子API实现的量子算法——Deutsch-Jozsa算法
    Prefix我是看这篇文章:​​不再神秘的量子计算,用Python就能实现(视频+代码),希望能run上面的代码。量子代码地址:​​https://github.com/llSourcell/quantum_computing​​结果......
  • Python @ 装饰器
    一、简单例子先看下面一个简单的例子程序t1清单deffunA(fn):print('A')fn()#fn实际就是funB(函数对象)@funAdeffunB():print('B')#if__name__=="__main......
  • python2 与python3 区别
    写文件下面这段代码,在python2中可以正常运行。但是python3会报错,因为是用w方式打开(而不是wb),则二进制数据不能写入该文件(会报错)。withopen("a.txt",'w')aspfile:pfil......
  • python中*的用法
    1、乘法运算符;*表示乘法,**表示次方2、函数形参表示可变参数;deffun(*a,**b):returna,b#a=(1,2,3)#b={'Name':xx,'age':yy}fun(1,2,3,Na......
  • 浅谈python容器、迭代器与生成器
    前言:for...in...循环时,与while不同的是,for可以自动访问容器中的下一个元素,这是为什么呢?#用while循环访问列表容器iter_a=iter(a)whileTrue:try:print(ne......
  • Python matplotlib 画图入门 10 画盒图 boxplot
     importnumpyasnpimportmatplotlib.pyplotasplt#generatesomerandomdatadata=np.random.randn(200)##产生200个标准正态分布数字,d=[data,data......