最近公司要往阿里云oss上傳視頻昆烁,大小差不多有200G吊骤,原先讓運(yùn)營(yíng)去一個(gè)一個(gè)的添加,但是這能麻煩死人静尼,所以就讓技術(shù)去批量上傳白粉。所以研究了一下用python往oss上傳視頻
首先需引用以下幾個(gè)模塊
pip install oss2
pip install tablib
pip install pyexcel-xlsx
其次因?yàn)楸镜氐囊曨l都是比如中文.mp4
這樣的,所以引入一個(gè)隨機(jī)字符串
import random
def generate_random_str(randomlength=8):
"""
生成一個(gè)指定長(zhǎng)度的隨機(jī)字符串
"""
random_str = ''
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
length = len(base_str) - 1
for i in range(randomlength):
random_str += base_str[random.randint(0, length)]
return random_str
因?yàn)槭俏募A里面套文件夾鼠渺,但是只上傳文件鸭巴,所以需要獲取子文件夾下面的視頻
代碼如下:
def upload(dir):
fs = os.listdir(dir)
for f in fs:
file = dir + "/" + f
if os.path.isdir(file):
upload(file)
else:
if 'DS_Store' not in file and 'png' not in f and 'JPG' not in f:
putAliyun(file, f)
備注:因?yàn)槲募A里面還有圖片,所以去除后綴為png
拦盹、JPG
的圖片鹃祖。因?yàn)橛玫氖莔ac上傳,所以文件夾里面有.DS_Store
普舆,所以也需要去除
所以這個(gè)的整個(gè)代碼如下:
#!/usr/bin/env python
# ! -*- coding:utf-8 -*-
import oss2
import random
import os
import tablib
import time
ossDir = '/Users/FQY/Desktop/upload'
key = XXX
secret = XXX
bucketname = XXX
dataset = tablib.Dataset()
header = ('title', 'url')
dataset.headers = header
def generate_random_str(randomlength=8):
"""
生成一個(gè)指定長(zhǎng)度的隨機(jī)字符串
"""
random_str = ''
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
length = len(base_str) - 1
for i in range(randomlength):
random_str += base_str[random.randint(0, length)]
return random_str
def getmkname(path):
remoteName = path.replace(ossDir, '')
dir_names = remoteName.split('/')
dir_names.pop()
res = filter(None, dir_names)
mkdir_name = '-'.join(res)
return mkdir_name
#獲得上傳的時(shí)長(zhǎng)
def progress_callback(bytes_consumed, total_bytes):
print('bytes_consumed is {}'.format(bytes_consumed))
print('total_bytes is {}'.format(total_bytes))
def putAliyun(path, f):
key = 'language/' + str(int(time.time())) + generate_random_str() + '.mp4'
auth = oss2.Auth(key, secret)
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', bucketname)
result = bucket.put_object_from_file(key=key, filename=path,progress_callback=progress_callback)
if result.status == 200:
aliyun = 'http://video.oss-cn-hangzhou.aliyuncs.com/{}'.format(key)
title = '【{}】{}'.format(getmkname(path), f.split('.mp4')[0])
dataset.append([title, aliyun])
else:
print('upload fail,error code', result.status)
def upload(dir):
fs = os.listdir(dir)
for f in fs:
file = dir + "/" + f
if os.path.isdir(file):
upload(file)
else:
if 'DS_Store' not in file and 'png' not in f and 'JPG' not in f:
putAliyun(file, f)
upload(ossDir)
myfile = open('/Users/FQY/Desktop/mydata_video.xlsx', 'wb')
myfile.write(dataset.xlsx)
myfile.close()
tablib的介紹恬口,可以觀看以下的文章
利用tablib校读、make_response 進(jìn)行文件的下載