You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化Python脚本从Artifactory批量拉取全部文件及文件夹?

实现Artifactory基础路径下全量内容下载(含文件夹结构)

直接基于Artifactory REST API实现递归遍历+下载,只需要输入基础路径就能拉取所有内容(含完整文件夹结构),替代原来硬编码路径的繁琐操作。

核心思路

  • 调用Artifactory的/api/storage/{repo_path}接口获取目标路径的结构,区分文件和子目录
  • 递归遍历所有子目录,在本地自动创建对应层级的文件夹
  • 对每个文件,通过API下载并保存到本地对应路径,保留完整目录结构

完整实现代码

import os
import requests

# 配置Artifactory信息,替换成你的实际地址和认证信息
ARTIFACTORY_URL = "http://your-artifactory-url/artifactory"
AUTH = ("username", "password")  # 也可使用API_KEY格式: ("api-key", "")

def get_artifactory_path_content(repo_path):
    """获取Artifactory路径下的所有内容(文件/子目录)"""
    url = f"{ARTIFACTORY_URL}/api/storage/{repo_path}"
    params = {"list": "1"}  # 开启目录列表模式
    response = requests.get(url, auth=AUTH)
    response.raise_for_status()  # 捕获请求错误
    return response.json()

def download_artifactory_content(base_repo_path, local_base_path):
    """递归下载Artifactory基础路径下的所有内容"""
    content = get_artifactory_path_content(base_repo_path)
    
    # 如果是单个文件,直接下载
    if "downloadUri" in content:
        os.makedirs(local_base_path, exist_ok=True)
        file_name = os.path.basename(base_repo_path)
        local_file_path = os.path.join(local_base_path, file_name)
        
        # 流式下载大文件,避免内存溢出
        with requests.get(content["downloadUri"], auth=AUTH, stream=True) as r:
            r.raise_for_status()
            with open(local_file_path, "wb") as f:
                for chunk in r.iter_content(chunk_size=8192):
                    f.write(chunk)
        print(f"已下载: {local_file_path}")
        return
    
    # 如果是目录,遍历所有子项
    if "children" in content:
        # 创建本地对应目录
        os.makedirs(local_base_path, exist_ok=True)
        for child in content["children"]:
            child_repo_path = f"{base_repo_path}/{child['uri'].lstrip('/')}"
            child_local_path = os.path.join(local_base_path, child["uri"].lstrip('/'))
            
            # 递归处理子目录/文件
            download_artifactory_content(child_repo_path, child_local_path)

# 使用示例
if __name__ == "__main__":
    # 替换成你的Artifactory基础路径(例如libs-release-local/my-project/)
    ARTIFACTORY_BASE_PATH = "libs-release-local/my-project/"
    # 替换成本地保存的基础路径
    LOCAL_BASE_PATH = "./artifactory_downloads"
    
    download_artifactory_content(ARTIFACTORY_BASE_PATH, LOCAL_BASE_PATH)
    print("全量下载完成")

关键改进点

  • 自动递归遍历:无需手动拼接子目录路径,API会返回所有层级的内容
  • 保留文件夹结构:本地路径完全对应Artifactory的目录层级
  • 大文件支持:用流式下载处理大文件,避免内存占用过高
  • 错误处理:加入请求错误捕获,下载过程更稳定

使用说明

  1. 替换代码中的ARTIFACTORY_URL、AUTH、ARTIFACTORY_BASE_PATH和LOCAL_BASE_PATH为你的实际信息
  2. 确保已安装requests库:pip install requests
  3. 运行脚本即可自动拉取所有内容

内容的提问来源于stack exchange,提问作者nsnro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:30:15