Back
Featured image of post 【Python脚本】对象储存OSS,静态网页批量替换上传

【Python脚本】对象储存OSS,静态网页批量替换上传

替换静态资源,且支持多级路径的Python脚本

每次更新静态页面资源时,都需要上传到阿里云OSS。一般情况,手动上传还算容易,但在遇到多级路径的时候,整个过程就非常麻烦。这里写了一个替换静态资源,且支持多级路径的脚本。

import oss2, os

def foo():
    # 登录
    auth = oss2.Auth('填写access key id', '填写access key secret')
    bucket = oss2.Bucket(auth, '填写上传oss的域名', '填写Bucket名称')

    # 删除所有原来OSS中的文件
    for b in oss2.ObjectIterator(bucket):
        bucket.delete_object(b.key)

    # 获取本地路径
    path_zips = []
    start_path = r'C:\Users\jsy\PycharmProjects\cms_front\dist' # 填写自己的路径
    for root, dirs, files in os.walk(start_path):
        path = [os.path.join(root, name) for name in files]
        rel_path = [os.path.relpath(p, start_path) for p in path]

        path_zip = zip(rel_path, path)
        path_zips.extend(path_zip)

    # 上传文件
    for rel_path, path in path_zips:
        bucket.put_object_from_file(rel_path.replace('\\', '/'), path)


if __name__ == '__main__':
    try:
        foo()
        print('上传成功!')
    except:
        print('出现异常!')
        input()
沪ICP备20004885号-2
jonathan.nuance@outlook.com
Built with Hugo
Theme Stack designed by Jimmy