GTD2020-05-31 icon indicating copy to clipboard operation
GTD2020-05-31 copied to clipboard

Python:自动化上传 OSS - Williams_Guozi - 博客园

Open kunpeng9 opened this issue 3 years ago • 0 comments

最近在学习 Python,为之庞大的第三方库感到震撼。今天分享一个 Python 自动化脚本,功能是将 H5 静态资源上传到 OSS,以方便实现 CDN 加速,我将其放在 Jenkins 自动发布中使用。该脚本不是我的原创,是前同事留下的,希望对需要的小伙伴有所帮助。

pip install oss2

accesskey,accesspassword,bucketname,ossBucket 需要根据自己账户情况作出调整




import os
import sys
import oss2


ossAuth = oss2.Auth('accesskey', 'accesspassword')
ossBucket = oss2.Bucket(ossAuth, 'oss-cn-hangzhou.aliyuncs.com', 'bucketname')


pathfile = sys.argv[1]


if len(sys.argv) == 3:
    ossDir = sys.argv[2] + "/"
else:
    ossDir = ""

ee = [1]
ee[0] = 1

ff = '550.jpg'



def list(dir):
    fs = os.listdir(dir)
    for f in fs:
        file = dir + "/" + f;
        print("file is" + ":" + file)
        if os.path.isdir(file):
            list(file)
        else:
            uploadDir(file)



def uploadDir(path_filename):
    print("------------------")
    print(path_filename)
    remoteName = ossDir + path_filename.split('//')[1]
    print("remoteName is" + ":" + remoteName)
    print('uploading..', path_filename, 'remoteName', remoteName)
    if (ee[0] == 0 and remoteName == ff):
        ee[0] = 1
    if 1 == ee[0]:
        result = ossBucket.put_object_from_file(remoteName, path_filename)
        print('http_status: {0}'.format(result.status))



def uploadFile(filename):
    remoteName = ossDir + os.path.basename(filename)
    print("remoteName is" + ":" + remoteName)
    print('uploading..', filename, 'remoteName', remoteName)
    if (ee[0] == 0 and remoteName == ff):
        ee[0] = 1
    if 1 == ee[0]:
        result = ossBucket.put_object_from_file(remoteName, filename)
        print('http_status: {0}'.format(result.status))



if os.path.isdir(pathfile):
    if pathfile.endswith('/'):
        pass
    else:
        pathfile += "/"
    print("it's a directory")
    list(pathfile)
elif os.path.isfile(pathfile):
    print("it's a normal file")
    uploadFile(pathfile)
else:
    print("it's a special file (socket, FIFO, device file)")

python /etc/ansible/scripts/bxq-online-oss.py $WORKSPACE/dist

kunpeng9 avatar Nov 12 '20 09:11 kunpeng9