使用python将工件上传到artifactory

时间:2014-07-16 14:15:06

标签: python python-requests artifactory

我正在尝试使用请求将工件上传到artfactory repo,但我收到405错误。我有一个工作的bash脚本来实现这个目标,但我真的需要一个python实现。

import os
import hashlib
import requests
from requests.auth import HTTPBasicAuth

username = 'me'
password = 'secrets'


target_file = '/home/me/app-1.0.0-snapshot.el6.noarch.rpm'

artifactory_url = 'https://artifactory.company.com/artifactory'

def get_md5(fin):
    md5 = hashlib.md5()
    with open(fin, 'rb') as f:
        for chunk in iter(lambda: f.read(8192), ''):
            md5.update(chunk)
    return md5.hexdigest()

def get_sha1(fin):
    sha1 = hashlib.sha1()
    with open(fin, 'rb') as f:
        for chunk in iter(lambda: f.read(8192), ''):
            sha1.update(chunk)
    return sha1.hexdigest()


def upload(fin):
    base_file_name = os.path.basename(fin)
    md5hash = get_md5(fin)
    sha1hash = get_sha1(fin)
    headers = {"X-Checksum-Md5": md5hash, "X-Checksum-Sha1": sha1hash}
    r = requests.post("{0}/{1}/{2}".format(artifactory_url, "yum-local", base_file_name),auth=(username,password), headers=headers, verify=False, data=open(fin, 'rb'))
    return r    

的bash

art_url="https://artifactory.company.com/artifactory"
user="user"
pass="password"


function upload {
    local_file_path=$1
    target_folder=$2
    if [ ! -f "$local_file_path" ]; then
    echo "ERROR: local file $local_file_path does not exists!"
    exit 1
    fi

    which md5sum || exit $?
    which sha1sum || exit $?

    md5Value="`md5sum "$local_file_path"`"
    md5Value="${md5Value:0:32}"
    sha1Value="`sha1sum "$local_file_path"`"
    sha1Value="${sha1Value:0:40}"
    fileName="`basename "$local_file_path"`"

    echo $md5Value $sha1Value $local_file_path

    echo "INFO: Uploading $local_file_path to $target_folder/$fileName"
    curl -i  -k -X PUT -u $user:$pass \
    -H "X-Checksum-Md5: $md5Value" \
    -H "X-Checksum-Sha1: $sha1Value" \
    -T "$local_file_path" \
    ${art_url}/"$target_folder/$fileName"
           }

upload "/projects/app.war" "libs-release-local/com/company/app/app-comp/1.0.0/"

3 个答案:

答案 0 :(得分:5)

第一件事就是我的bash脚本在你的python脚本使用PUT时使用了POST

我看到的唯一其他潜在问题是您构建网址的方式完全不同。

在bash脚本中,您创建的URL最终为

https://artifactory.company.com/artifactory/libs-release-local/com/company/app/app-comp/1.0.0//app.war

在你正在使用的python脚本中

https://artifactory.company.com/artifactory/yum-local/app-1.0.0-snapshot.el6.noarch.rpm

另外,请注意yum-local已硬编码到您生成的每个网址中。


除此之外,您的get_md5get_sha1函数可以更简单地编写,因为文件对象是可迭代的,例如,

with open(fin, 'rb') as f:
    for chunk in f:
        md5.update(chunk)

答案 1 :(得分:2)

错误405代表使用错误的HTTP方法。 根据{{​​3}},工件部署应该使用PUT完成。

这意味着您无法使用requests.post,但需要使用requests.put

答案 2 :(得分:0)

你的迭代器不会在 python3 中停止,因为它们与 '' 相比,它应该是 b''