上传指定本地文件目录中的所有文件到OSS指定Bucket文件夹
因为OSS可以绑定域名托管静态网页,所以我们项目的前端文件就放到上面啦。但是控制台是不支持本地文件夹上传的,所以用python写了一个脚本方便前端同事上传,随着项目逐渐丰满起来,文件也修改了两次以方便使用,在这里贴出来,有同样需要的也可以改改拿去用,省点时间。
目前是5个项目(5个目录),2种环境(两个OSS-Bucket)。启动后输入项目名和环境,就自动找到预先配置好的本地目录,将其整个上传到OSS目录。注意:我的环境是windows7、 python3.5。python2.7需要将 input替换为raw_input,OSX需要修改一些’\‘为’/’。
import os
import sys
#pip install oss2
import oss2
#本地路径
basedirChain=r'D:\projects\backend-chain\dist'
basedirStore=r'D:\projects\backend-store\dist'
basedirAdmin=r'D:\projects\backend-admin\dist'
basedirChannel=r'D:\projects\backend-channel\dist'
basedirShare=r'D:\projects\wx-record\dist'
projectList = ['chain','store','admin','sharePage','channel']
dirList = [basedirChain,basedirStore,basedirAdmin,basedirShare,basedirChannel]
environmentList = ['test','prod']
bucket=''
ossDir=''
basedir=''
#id,key
ossAuth=oss2.Auth('accessKeyId','accessKeySecret')
#bucketName
ossBucket = None
def checkInput(pro,env):
if pro in projectList and env in environmentList:
print('>>>>>>>>>>>>>>>>>Upload:'+pro+'-'+env+'---Start!')
global ossDir,basedir,bucket,ossBucket
ossDir, basedir= pro,dirList[projectList.index(pro)]
bucket = 'your-prod-backend' if env=='prod' else 'your-test-backend'
ossBucket = oss2.Bucket(ossAuth,'http://oss-cn-hangzhou.aliyuncs.com',bucket)
list(basedir)
input("Successfully! Prease <Enter>")
else:
print('Error! Check your input!')
getInput()
def getInput():
project = input('Please Input Project('+'/'.join(projectList)+'):')
environment = input('Please Input Environment('+'/'.join(environmentList)+'):')
checkInput(project,environment)
def uploadFile(file):
remoteName = ossDir + file.replace(basedir,'').replace('\\','/')
print ('uploading..',file,'remoteName',remoteName)
result=ossBucket.put_object_from_file(remoteName,file)
print('http status: {0}'.format(result.status))
def list(dir):
fs=os.listdir(dir)
for f in fs:
file=dir+'\\'+f;
if os.path.isdir(file):
list(file)
else:
uploadFile(file)
if __name__ == '__main__':
getInput()