python 调用 oss sdk

#cython: language_level=3
import sys
import oss2
import logging
from itertools import islice


OSS_BUCKEET_NAME = "xxxxx"
OSS_AK_ID = "xxxxxxxxxx"
OSS_AK_SECRET = "xxxxxxxxxxxx"
OSS_ENDPOINT = "https://oss-cn-beijing.aliyuncs.com"
oss2.set_file_logger("./oss.log", 'oss2', logging.INFO)
auth = oss2.Auth(OSS_AK_ID,OSS_AK_SECRET)
bucket = oss2.Bucket(auth=auth, endpoint=OSS_ENDPOINT, bucket_name=OSS_BUCKEET_NAME)


def percentage(consumed_bytes, total_bytes):
    if total_bytes:
        rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
        print('\r{0}% '.format(rate), end='')
        sys.stdout.flush()


def download(source_file_list):

    try:
        if "," in source_file_list:
            source_file_list = source_file_list.split(",")
            for source_file in source_file_list:
                path = source_file.split("/")[-1]
                oss2.resumable_download(bucket, source_file,  path, progress_callback=percentage)
        else:
            path = source_file_list.split("/")[-1]
            oss2.resumable_download(bucket, source_file_list, path, progress_callback=percentage)
    except oss2.exceptions as e:
        print('status={0}, request_id={1}'.format(e.status, e.request_id))


def list_file():
    for b in islice(oss2.ObjectIterator(bucket=bucket, prefix='test/'), 20):
        print(b.key)


if __name__ == '__main__':
    help = """
    HELP:
    ====================================================================================
    list file: Usage: Example: ./oss list
    Download one file: Usage: Example: ./oss test/test.txt 
    Download muti files: Usage: Example: ./oss test/test111.txt,test/test222.txt 
    ====================================================================================
    """
    print(help)
    if sys.argv[1] == "list":
        list_file()
    else:
        download(sys.argv[1])

 

posted @ 2022-06-20 18:34  力王7314  阅读(294)  评论(0编辑  收藏  举报