# -*- coding: utf8 -*-
import os
import requests
import time
requests.packages.urllib3.disable_warnings() # 禁用SSL警告
def download_files_from_urls(directory):
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
url = construct_url(file_path)
download_file(url, saveDirectory + os.path.relpath(file_path, directory))
def construct_url(file_path):
# 在这里根据文件路径构建对应的URL
# 示例:假设URL根路径为https://example.com/files/
# 文件路径为path/to/file.txt,则对应URL为https://example.com/files/path/to/file.txt
base_url = 'https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/'
relative_path = os.path.relpath(file_path, directory) # 计算相对路径
url = base_url + relative_path.replace(os.sep, '/') # 将路径分隔符替换为URL中的斜杠
return url
def download_file(url, file_path):
print(url)
for i in range(3):
try:
response = requests.get(url, verify=False)
if response.status_code == 200:
# 创建父级目录
parent_dir = os.path.dirname(file_path)
if not os.path.exists(parent_dir):
os.makedirs(parent_dir)
with open(file_path, 'wb') as file:
file.write(response.content)
print("下载成功:{}, 保存路径: {}".format(file_path, file.name))
return # 下载成功后退出循环
else:
print("下载失败:{}".format(file_path))
return # 正常失败退出循环
except Exception as e:
print("下载失败:{},进行第{}次重试".format(file_path, i+1))
print("错误信息:", str(e))
time.sleep(1) # 延迟1秒后进行重试
print("下载失败:{},已超过重试次数".format(file_path))
# 需要下载文件的根目录
directory = '/home/viewer/t'
# 需要保存的目录
saveDirectory = '/home/viewer/'
download_files_from_urls(directory)
最后修改:2024 年 10 月 29 日
© 允许规范转载