日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python:自动化上传OSS

發布時間:2025/3/16 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python:自动化上传OSS 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

簡介

最近在學習Python,為之龐大的第三方庫感到震撼。今天分享一個Python 自動化腳本,功能是將H5靜態資源上傳到OSS,以方便實現CDN加速,我將其放在Jenkins自動發布中使用。該腳本不是我的原創,是前同事留下的,希望對需要的小伙伴有所幫助。

安裝阿里云第三方庫

pip install oss2

腳本說明

accesskey,accesspassword,bucketname,ossBucket 需要根據自己賬戶情況作出調整

腳本內容

#!/usr/bin/python # -*- coding:utf8 -*-import os import sys import oss2# 阿里云相關的token ossAuth = oss2.Auth('accesskey', 'accesspassword') ossBucket = oss2.Bucket(ossAuth, 'oss-cn-hangzhou.aliyuncs.com', 'bucketname')# 本地需要上傳的文件或者目錄,sys.argv: 實現從程序外部向程序傳遞參數。 pathfile = sys.argv[1]# 判斷是否輸入目標目錄(在oss中的目錄,程序會自動創建),如果沒有輸入目標目錄,則直接上傳文件到oss的根目錄下 if len(sys.argv) == 3:ossDir = sys.argv[2] + "/" else:ossDir = ""ee = [1] ee[0] = 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)# 上傳帶目錄的文件到OSS 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] = 1if 1 == ee[0]:result = ossBucket.put_object_from_file(remoteName, path_filename)print('http_status: {0}'.format(result.status))# 上傳文件到OSS 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] = 1if 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('/'):passelse: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

參考文檔

  • python之sys模塊詳解:https://www.cnblogs.com/cherishry/p/5725184.html
  • Aliyun OSS SDK for Python:https://aliyun-oss-python-sdk.readthedocs.io/en/stable
  • aliyun-oss-python-sdk Github地址:https://github.com/aliyun/aliyun-oss-python-sdk/tree/master/oss2

轉載于:https://www.cnblogs.com/William-Guozi/p/python-oss.html

總結

以上是生活随笔為你收集整理的Python:自动化上传OSS的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。