i0110 commited on
Commit
470e738
·
verified ·
1 Parent(s): 9cabe1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -40
app.py CHANGED
@@ -7,47 +7,77 @@ from urllib.parse import urlparse
7
  # 创建 Flask 应用实例
8
  app = Flask(__name__)
9
 
10
- @app.route('/', methods=['GET', 'POST'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def index():
12
- if request.method == 'POST':
13
- github_url = request.form['github_url']
14
-
15
- # Parse the GitHub URL to extract owner, repo, branch, and folder path
16
- parsed_url = urlparse(github_url)
17
- path_parts = parsed_url.path.strip('/').split('/')
18
-
19
- if len(path_parts) < 5 or path_parts[2] != 'tree':
20
- return "Error: Invalid GitHub URL format. Please provide a valid link to a folder."
21
-
22
- owner = path_parts[0]
23
- repo = path_parts[1]
24
- branch = path_parts[3]
25
- folder_path = '/'.join(path_parts[4:])
26
-
27
- # Construct the API URL to get the contents of the folder
28
- api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{folder_path}?ref={branch}"
29
-
30
- response = requests.get(api_url)
31
- if response.status_code != 200:
32
- return "Error: Unable to fetch the folder contents."
33
-
34
- files = response.json()
35
- if not isinstance(files, list):
36
- return "Error: The provided path is not a folder."
37
-
38
- # Create a zip file in memory
39
- zip_buffer = BytesIO()
40
- with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) as zip_file:
41
- for file in files:
42
- if file['type'] == 'file':
43
- file_content = requests.get(file['download_url']).content
44
- zip_file.writestr(file['name'], file_content)
45
-
46
- # Prepare the zip file for download
47
- zip_buffer.seek(0)
48
- return send_file(zip_buffer, download_name=f"{repo}_{folder_path.replace('/', '_')}.zip", as_attachment=True)
49
-
50
- return render_template('index.html')
51
 
52
  if __name__ == "__main__":
53
  app.run(host="0.0.0.0", port=5000)
 
7
  # 创建 Flask 应用实例
8
  app = Flask(__name__)
9
 
10
+ def is_directory(url):
11
+ """检查 URL 是否指向 GitHub 文件夹"""
12
+ pathname = urlparse(url).path.split("/")
13
+ return "tree" in pathname and len(pathname) > 5
14
+
15
+ def get_repo_info_from_url(url):
16
+ """从 GitHub URL 中提取仓库信息"""
17
+ pathname = urlparse(url).path.split("/")
18
+ owner = pathname[1]
19
+ repo = pathname[2]
20
+ branch = pathname[4]
21
+ folder_path = "/".join(pathname[5:])
22
+ return owner, repo, branch, folder_path
23
+
24
+ def fetch_folder_contents(owner, repo, branch, folder_path):
25
+ """获取文件夹内容"""
26
+ api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{folder_path}?ref={branch}"
27
+ response = requests.get(api_url)
28
+ if response.status_code != 200:
29
+ raise Exception(f"Unable to fetch folder contents: {response.status_code}")
30
+ return response.json()
31
+
32
+ def download_file(file_url):
33
+ """下载单个文件"""
34
+ response = requests.get(file_url)
35
+ if response.status_code != 200:
36
+ raise Exception(f"Unable to download file: {response.status_code}")
37
+ return response.content
38
+
39
+ def create_zip(files):
40
+ """将文件打包成 ZIP"""
41
+ zip_buffer = BytesIO()
42
+ with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
43
+ for file_name, file_content in files.items():
44
+ zip_file.writestr(file_name, file_content)
45
+ zip_buffer.seek(0)
46
+ return zip_buffer
47
+
48
+ @app.route("/", methods=["GET", "POST"])
49
  def index():
50
+ if request.method == "POST":
51
+ github_url = request.form["github_url"]
52
+
53
+ if not is_directory(github_url):
54
+ return "Error: Please provide a valid GitHub folder URL."
55
+
56
+ try:
57
+ # 提取仓库信息
58
+ owner, repo, branch, folder_path = get_repo_info_from_url(github_url)
59
+
60
+ # 获取文件夹内容
61
+ contents = fetch_folder_contents(owner, repo, branch, folder_path)
62
+
63
+ # 下载所有文件
64
+ files = {}
65
+ for item in contents:
66
+ if item["type"] == "file":
67
+ file_content = download_file(item["download_url"])
68
+ files[item["name"]] = file_content
69
+
70
+ # 打包成 ZIP
71
+ zip_buffer = create_zip(files)
72
+ return send_file(
73
+ zip_buffer,
74
+ download_name=f"{repo}_{folder_path.replace('/', '_')}.zip",
75
+ as_attachment=True,
76
+ )
77
+ except Exception as e:
78
+ return f"Error: {str(e)}"
79
+
80
+ return render_template("index.html")
 
 
 
 
 
 
 
 
81
 
82
  if __name__ == "__main__":
83
  app.run(host="0.0.0.0", port=5000)