当前位置:   article > 正文

通过Python下载Github最新Release_下载最新githubreleases

下载最新githubreleases

功能1:将项目的所有者,名称,版本信息,本机保存的地址。保存到json文件中。
功能2:json中可收录多个项目的信息。点击即可更新多个项目。
功能3:将json文件中的版本信息与api.github中的最新版进行比较,若有更新的版本,就会下载最新的release,并同步更新json。

功能4:指定下载的文件名称。

python、json和打包的exe,已压缩,可点击下载icon-default.png?t=N7T8https://wooo1.lanzoul.com/iO0Ui1z3wvcf

以下是Python代码

  1. import os
  2. import sys
  3. import json
  4. import py7zr
  5. import zipfile
  6. import urllib3
  7. import logging
  8. import requests
  9. PROJECTS_JSON_FILE = "projects.json"
  10. # 禁用urllib3库产生的不安全请求警告
  11. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  12. # 配置日志输出格式和级别,并记录到文件和控制台
  13. log_file = "log.txt"
  14. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filename=log_file)
  15. console_handler = logging.StreamHandler(sys.stdout)
  16. console_handler.setLevel(logging.INFO)
  17. logging.getLogger().addHandler(console_handler)
  18. def download_release_files(owner, repo, version, save_path, file=None):
  19. logging.info("开始下载发布文件...")
  20. # 获取最新发布版本的下载链接
  21. url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
  22. response = requests.get(url, verify=False)
  23. if response.status_code == 200:
  24. release = response.json()
  25. latest_version = release['tag_name']
  26. logging.info(f"当前版本号 {version}")
  27. logging.info(f"最新版本号 {latest_version}")
  28. if version == latest_version:
  29. logging.info("当前版本已是最新版本,无需下载。")
  30. return True
  31. assets = release['assets']
  32. for asset in assets:
  33. file_url = asset['browser_download_url']
  34. file_name = asset['name']
  35. if file and file_name != file:
  36. continue
  37. file_save_path = os.path.join(save_path, file_name)
  38. # 下载文件时添加进度日志
  39. with requests.get(file_url, stream=True, verify=False) as r:
  40. try:
  41. r.raise_for_status()
  42. except requests.exceptions.HTTPError:
  43. logging.error(f"无法下载文件 {file_name}")
  44. continue
  45. logging.info(f"正在下载文件 {file_name}")
  46. with open(file_save_path, 'wb') as f:
  47. total_size = int(r.headers.get('content-length', 0))
  48. downloaded_size = 0
  49. for chunk in r.iter_content(chunk_size=8192):
  50. if chunk:
  51. f.write(chunk)
  52. downloaded_size += len(chunk)
  53. progress = int(downloaded_size / total_size * 100)
  54. logging.info(f"下载进度 {progress}%")
  55. logging.info(f"成功下载文件 {file_name}")
  56. # 检查文件是否是压缩文件并进行解压
  57. if file_name.endswith(".zip"):
  58. logging.info(f"开始解压文件 {file_name}")
  59. with zipfile.ZipFile(file_save_path, 'r') as zip_ref:
  60. zip_ref.extractall(save_path)
  61. # 解压成功后删除压缩文件
  62. if os.path.exists(file_save_path):
  63. os.remove(file_save_path)
  64. logging.info(f"成功删除压缩文件 {file_name}")
  65. elif file_name.endswith(".7z"):
  66. logging.info(f"开始解压文件 {file_name}")
  67. with py7zr.SevenZipFile(file_save_path, mode='r') as z:
  68. z.extractall(save_path)
  69. # 解压成功后删除压缩文件
  70. if os.path.exists(file_save_path):
  71. os.remove(file_save_path)
  72. logging.info(f"成功删除压缩文件 {file_name}")
  73. return True
  74. else:
  75. logging.error("无法获取发布信息。")
  76. return False
  77. def get_latest_version(owner, repo):
  78. logging.info("开始获取最新版本号...")
  79. # 获取最新发布版本号
  80. url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
  81. response = requests.get(url, verify=False)
  82. if response.status_code == 200:
  83. release = response.json()
  84. if 'tag_name' in release:
  85. latest_version = release['tag_name']
  86. logging.info(f"最新版本号 {latest_version}")
  87. return latest_version
  88. else:
  89. logging.error("无法获取最新版本号。")
  90. else:
  91. logging.error("无法获取发布信息。")
  92. def update_projects(json_file):
  93. logging.info("开始更新项目列表...")
  94. # 更新项目列表中的每个项目
  95. with open(json_file, 'r', encoding='utf-8') as f:
  96. data = json.load(f)
  97. updated_projects = []
  98. for project in data["projects"]:
  99. owner = project["owner"]
  100. name = project["name"]
  101. version = project["version"]
  102. save_path = project["save_path"]
  103. file = project.get("file")
  104. logging.info(f"处理项目 {owner}/{name}")
  105. if not os.path.exists(save_path):
  106. os.makedirs(save_path)
  107. project_file = os.path.join(save_path, name)
  108. if not os.path.isfile(project_file):
  109. # 如果项目文件不存在,则尝试下载
  110. if download_release_files(owner, name, version, save_path, file):
  111. logging.info(f"成功下载项目 {owner}/{name}")
  112. version = get_latest_version(owner, name)
  113. else:
  114. logging.error(f"无法下载项目 {owner}/{name}")
  115. updated_projects.append({
  116. "owner": owner,
  117. "name": name,
  118. "version": version,
  119. "save_path": save_path,
  120. "file": file
  121. })
  122. updated_data = {
  123. "projects": updated_projects
  124. }
  125. save_projects_to_json(updated_data, json_file)
  126. def save_projects_to_json(data, json_file):
  127. logging.info("保存更新后的项目列表...")
  128. # 将更新后的项目列表保存到JSON文件中
  129. with open(json_file, 'w', encoding='utf-8') as f:
  130. json.dump(data, f, indent=4, ensure_ascii=False)
  131. if __name__ == "__main__":
  132. logging.info("开始更新项目...")
  133. update_projects(PROJECTS_JSON_FILE)
  134. logging.info("项目更新完成.")
  135. logging.shutdown()

以下是JSON文件

  1. {
  2. "projects": [
  3. {
  4. "owner": "2dust",
  5. "name": "v2rayN",
  6. "version": "6.33",
  7. "save_path": "D:\\加速",
  8. "file": "v2rayN.zip"
  9. },
  10. {
  11. "owner": "6yy66yy",
  12. "name": "legod-auto-pause",
  13. "version": "v2.2.1",
  14. "save_path": "D:\\加速\\雷神加速器\\自动暂停",
  15. "file": ""
  16. },
  17. {
  18. "owner": "R3nzTheCodeGOD",
  19. "name": "R3nzSkin",
  20. "version": "v3.2.7",
  21. "save_path": "D:\\Game\\GameTools\\LOL\\R3nzSkin",
  22. "file": ""
  23. },
  24. {
  25. "owner": "rumi-chan",
  26. "name": "Sakura",
  27. "version": "v1.0.2",
  28. "save_path": "D:\\Game\\GameTools\\LOL\\Sakura",
  29. "file": ""
  30. },
  31. {
  32. "owner": "cangzhang",
  33. "name": "champ-r",
  34. "version": "v2.0.2-b7",
  35. "save_path": "D:\\Game\\GameTools\\LOL\\ChampR\\V2",
  36. "file": ""
  37. },
  38. {
  39. "owner": "H4rry217",
  40. "name": "AimRobotLite",
  41. "version": "V2.0.7",
  42. "save_path": "D:\\Game\\GameTools\\BFV\\ARL",
  43. "file": ""
  44. }
  45. ]
  46. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/888809
推荐阅读
相关标签
  

闽ICP备14008679号