文档中心 > 快速入门
快速入门

最近更新时间:2022-07-25

本节介绍如何快速使用 UOS Python SDK 完成常见操作,如创建存储空间、上传文件、下载文件等。

本工程的更多用法请参考以下方式:

查看 sample 目录(包含上传本地文件,下载文件,分片上传,详情请点击查看


创建桶

对象存储桶(Bucket)是存储对象(Object)的容器。对象都隶属于桶。

以下代码用于创建桶:

from src.ossConfig import ossConfig

import unicloud_oss.Oss as Oss


access_key = 'XXXXXXXXX'

secret_key = 'XXXXXXXXXXXXXXXXXXX'

endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'

config = ossConfig(access_key,secret_key,endpoint_url)


bucket_name = 'bucket_name'


if Oss.bucket_exists(config, bucket_name):

    print("bucket %s already exists!" %bucket_name)


if Oss.create_bucket(config, bucket_name):

    print('Done!')

else:

    print('Error!')


上传文件

以下代码用于将指定的本地文件上传到UOS:

from src.ossConfig import ossConfig

import unicloud_oss.Oss as Oss


access_key = 'XXXXXXXXX'

secret_key = 'XXXXXXXXXXXXXXXXXXX'

endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'

config = ossConfig(access_key,secret_key,endpoint_url)


bucket_name = 'test1'

object_name = 'mytestput0212'

filename = 'C:\\test\\1084.iso'


if Oss.put_object(config, bucket_name, object_name, filename):

    print("put object sucess!")

else:

    print("put object failed!")


# 若要指定对象权限与存储类型,可在调用函数时指定

if Oss.put_object(config, bucket_name, object_name, filename, ACL='public-read', StorageClass='STANDARD'):

    print("put object sucess!")

else:

    print("put object failed!")


下载指定文件

以下代码用于将指定的UOS文件下载至本地:

from src.ossConfig import ossConfig

import unicloud_oss.Oss as Oss


access_key = 'XXXXXXXXX'

secret_key = 'XXXXXXXXXXXXXXXXXXX'

endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'

config = ossConfig(access_key,secret_key,endpoint_url)


bucket_name = 'test1'

object_name = 'mytestput1'

filename = 'D:\\test\\aaa.py'


if Oss.download_object(config, bucket_name, object_name, filename):

    print("download object sucess!")

else:

    print("download object failed!")


列举文件

以下代码用于列举指定UOS下的文件:

from src.ossConfig import ossConfig

import unicloud_oss.Oss as Oss


access_key = 'XXXXXXXXX'

secret_key = 'XXXXXXXXXXXXXXXXXXX'

endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'

config = ossConfig(access_key,secret_key,endpoint_url)


bucket_name = 'test1'


objects = Oss.list_objects(config, bucket_name)

if objects is not None:

    # 列出文件名称

    for obj in objects:

        print(obj["Key"])

else:

    print("ERROR!")


删除文件

以下代码用于删除UOS中的指定文件:

from src.ossConfig import ossConfig

import unicloud_oss.Oss as Oss


access_key = 'XXXXXXXXX'

secret_key = 'XXXXXXXXXXXXXXXXXXX'

endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'

config = ossConfig(access_key,secret_key,endpoint_url)


bucket_name = 'test1'

object_name = 'mytestput0723'


if Oss.delete_object(config,bucket_name,object_name):

    print('Delete Object Success')

else:

    print('Delete Failed')