递归下载Jfrog Artifactory 目录下所有文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-05-02 18:24:37
# @Author  : Zhu Robin (robin.zhu@nokia-sbell.com)

from json import loads
import re
from concurrent.futures import ThreadPoolExecutor
import os
import requests
from scm_tools.logger import get_logger
from os import path as osp
from bs4 import BeautifulSoup
from zipfile import ZipFile
import md5
import shutil
import fire

class PhraseArt(object):
    """Phrase art url and make it more ease to operator.

    api return of a dir:
    {
      "repo" : "******",
      "path" : "/aa/aa",
      "created" : "2018-05-02T20:04:33.880+08:00",
      "createdBy" : "**",
      "lastModified" : "2018-05-02T20:04:33.880+08:00",
      "modifiedBy" : "**",
      "lastUpdated" : "2018-05-02T20:04:33.880+08:00",
      "children" : [ {
        "uri" : "/__init__.py",
        "folder" : false
      }, {
        "uri" : "/__init__.pyc",
        "folder" : false
      }, {
        "uri" : "/a.py",
        "folder" : false
      }, {
        "uri" : "/a.pyc",
        "folder" : false
      } ],
      "uri" : "https://******:443/artifactory/api/storage/******/aa/aa"
    }

    api return of a file:
    {
      "repo" : "******",
      "path" : "/aa/aa/__init__.py",
      "created" : "2018-05-02T20:04:33.881+08:00",
      "createdBy" : "**",
      "lastModified" : "2018-05-02T20:04:33.000+08:00",
      "modifiedBy" : "**",
      "lastUpdated" : "2018-05-02T20:04:33.000+08:00",
      "downloadUri" : "https://******:443/artifactory/******/aa/aa/__init__.py",
      "mimeType" : "text/x-python",
      "size" : "0",
      "checksums" : {
        "sha1" : "da39a3ee5e6b4b0d3255bfef95601890afd80709",
        "md5" : "d41d8cd98f00b204e9800998ecf8427e",
        "sha256" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
      },
      "originalChecksums" : {
        "sha1" : "da39a3ee5e6b4b0d3255bfef95601890afd80709",
        "md5" : "d41d8cd98f00b204e9800998ecf8427e",
        "sha256" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
      },
      "uri" : "https://******:443/artifactory/api/storage/******/aa/aa/__init__.py"
    }
    """
    api_str = "/artifactory/api/storage/"

    def __init__(self, url):
        if url.endswith("/"):
            url = url[:-1]
        if self.api_str in url:
            self.api_url = url
            self.url = url.replace(self.api_str, "/artifactory/")
        else:
            self.url = url
            self.api_url = url.replace("/artifactory/", self.api_str)
        r = requests.get(self.api_url)
        if r.status_code == 200:
            self.data = loads(r.content)
            for k, v in self.data.items():
                setattr(self, k, v)
        self.path = self.path[1:]
        self.return_full_path = True

    def __getattribute__(self, key):
        # called when use like PhraseArt.somekey
        try:
            return super(PhraseArt, self).__getattribute__(key)
        except AttributeError:
            raise

    @property
    def md5(self):
        return self.checksums["md5"]

    @property
    def sha1(self):
        return self.checksums["sha1"]

    @property
    def sub_file(self):
        if self.return_full_path == True:
            replace_str = self.url + "/"
        else:
            replace_str = ""
        return [one["uri"].replace("/", replace_str) for one in self.children if one["folder"] == False]

    @property
    def sub_dir(self):
        if self.return_full_path == True:
            replace_str = self.url + "/"
        else:
            replace_str = ""
        return [one["uri"].replace("/", replace_str) for one in self.children if one["folder"] == True]

    @property
    def sub_api_guys(self):
        if self.return_full_path == True:
            replace_str = self.api_url + "/"
        else:
            replace_str = ""
        return [one["uri"].replace("/", replace_str) for one in self.children]

    @property
    def sub_guys(self):
        if self.return_full_path == True:
            replace_str = self.url + "/"
        else:
            replace_str = ""
        return [one["uri"].replace("/", replace_str) for one in self.children]


class DownloadArt(PhraseArt):
    """docstring for DownloadArt"""

    def __init__(self, url):
        super(DownloadArt, self).__init__(url)
        p = re.compile(r'(.*/artifactory/[^\/]*/)')
        self.art_project = p.findall(self.url)[0]
        self.art_dir = url.replace(self.art_project,"")
        if "." in self.art_dir.split("/")[-1]:
            self.art_dir = "/".join(self.art_dir.split("/")[:-1])
        self.temp = list()
        self.sub = list()
        self.temp.append(self.uri)
        self.walk_once()
        

    def walk_once(self):
        if self.temp:
            one = self.temp.pop()
            p = PhraseArt(one)
            if not hasattr(p, "children"):
                self.sub.append(p)
            else:
                self.temp += p.sub_api_guys
            self.walk_once()

    def download_artifactory_dir(self, dir_path=None):
        pass


    @property
    def all_sub_files(self):
        return [p.path for p in self.sub]

    @property
    def all_sub_urls(self):
        return [p.url for p in self.sub]


class DlArtTool(DownloadArt):
    """Docstring for DownloadArtTool."""

    def __init__(self, url):
        super(DlArtTool, self).__init__(url)

    def download_art(self, dir_path=None):
        # """Url of art."""
        if dir_path is not None:
            map(lambda x: setattr(x, "path", x.path.replace(self.art_dir, dir_path, 1)), self.sub)
        datas = [(one.url, one.path, one.md5) for one in self.sub]
        with ThreadPoolExecutor(max_workers=6) as executor:
            executor.map(download_file, *zip(*datas))


def download_artifactory(url, dir_path=""):
    """Url: artifactory url ."""
    artdl = DlArtTool(url)
    if len(artdl.sub) == 1:
        _info("I guess this is a file...")
        dir_path = osp.realpath(dir_path)
        artdl.download_art(dir_path)
        return osp.join(dir_path, url.split("/")[-1])
    else:
        _info("This is a art dir...")
        artdl.download_art(dir_path)
        return dir_path


def download_file(url, file_name=None, md5_value=None):
    basename, url = format_url(url)
    if file_name is None:
        file_name = osp.join(os.getcwd(), basename)
    file_path = osp.dirname(file_name)
    if not osp.exists(file_path):
        os.makedirs(file_path)
    with open(file_name, "wb") as f:
        r = requests.get(url, stream=True, proxies=no_proxies)
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
    full_name = osp.realpath(file_name)
    _info("download {0} to {1} finished".format(url, full_name))
    if md5_value is None:
        return full_name
    if check_md5sum(full_name, md5_value):
        return full_name
    else:
        raise SystemError("check_md5sum failed")

def check_md5sum(file_name, old_value=None):
    assert not osp.isdir(file_name), "{} must not a dir".format(file_name)
    if old_value is None:
        return True
    m = md5.new()
    with open(file_name, "rb") as f:
        for line in f:
            m.update(line)
    real_value = m.hexdigest()
    if real_value == old_value:
        _info("check_md5sum of {} success".format(file_name))
        return True
    else:
        _error("check_md5sum of {} failed".format(file_name))
        return False



if __name__ == '__main__':
    download_artifactory(url,some_path)

功能简介:

自动递归遍历artifactory里面的文件夹,组成文件数据列表映射到download_file 功能函数里面。
download_file 根据是否传入校验值来觉得是否进行md5 校验。

Tips:

  • Jfrog Artifactory 有个temp缓存的坑,jfrog下载文件的时候默认是缓存到/temp/目录下的,如果下载文件几个G,temp又很小的话,你懂得...。可以通过export TMPDIR="/large——dir" 来缓解尴尬。
  • 上传的功能下次做...
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容