python上传文件至阿里oss[备份数据]

来源:赵克立博客 分类: Python 标签:Python模块备份Python发布时间:2019-06-12 11:05:40最后更新:2019-06-12 17:46:05浏览:1634
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2019-06-12 17:46:05
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

使用前先安装oss2模块

pip install oss2

两个参数第一个本地绝对路径,第二个远程路径,注意第一个字符不要使用 / 

import os
import oss2
import sys
"""进度条回调函数,计算当前完成的百分比
:param consumed_bytes: 已经上传/下载的数据量
:param total_bytes: 总数据量
"""
def percentage(consumed_bytes, total_bytes):
    if total_bytes:
        sys.stdout.write('{0:.2f}%  {1:.2f}/{2:.2f}M\r'.format(100 * (consumed_bytes / total_bytes),
                                                               consumed_bytes / 1000000, total_bytes / 1000000))
        sys.stdout.flush()
        
# 本地路径 D:/a/a.zip
# 远程路径 bak/a/
# 文件名自动取本地路径文件名
def uploadoss(localfile, remotePath):
    if not os.path.exists(localfile):
        print('localfile is not exists!')
        return
    AccessKeyID = 'LTA******MeT'
    AccessKeySecret = 'aOLFL***********VAuXA1sKGKB'
    endpoint = 'oss-cn********.com'
    bucketName = 'xi********ve'
    print("start uploadoss...")
    auth = oss2.Auth(AccessKeyID, AccessKeySecret)
    bucket = oss2.Bucket(auth, endpoint, bucketName, enable_crc=False)
    osspath = remotePath + os.path.basename(localfile)
    print("uploading to %s" % (osspath))
    with open(localfile, 'rb') as fileobj:
        bucket.put_object(osspath, fileobj, progress_callback=percentage)
    print('\nuploadoss success!')
if __name__ == '__main__':
    uploadoss('E:/wok.zip', 'bak/a/')
    input('...')

1906121560308749191461.png


微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python