阿里云使用

oss 对象存储 #

Python SDK #

pip install oss2
export OSS_ACCESS_KEY_ID=SIHDoisdhuasuiUGDS
export OSS_ACCESS_KEY_SECRET=asdih213asHSIDH2e1

一、Auth #

import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice

auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

二、Bucket #

bucket_info 字段说明 #

字段type注释
{bucket_info.name}Bucket的名称
{bucket_info.storage_class}Bucket的存储类型
{bucket_info.creation_date}Bucket的创建时间
{bucket_info.intranet_endpoint}Bucket的内网Endpoint
{bucket_info.extranet_endpoint}Bucket的外网Endpoint
{bucket_info.owner.id}Bucket的拥有者ID
{bucket_info.acl.grant}Bucket的ACL授权
{bucket_info.data_redundancy_type}Bucket的数据冗余类型
{bucket_info.access_monitor}Bucket的访问跟踪状态

代码示例 #

# 查看Bucket
service = oss2.Service(auth, 'oss-ap-xiaomengmai-1.aliyuncs.com')
for b in oss2.BucketIterator(service):
	print(b.name)

# bucket信息
bucket = oss2.Bucket(auth, 'oss-ap-xiaomengmai-1.aliyuncs.com', '{bucket_name}')
bucket_info = bucket.get_bucket_info()

文件操作 #

# 写入字符串
result = bucket.put_object('exampleobject.txt', 'Hello OSS')
bucket.object_exists('exampleobject.txt')
##> True

# 查看object列表
[i.key for i in bucket.list_objects("").object_list]

递归查看 - 有无/的区别 #

for obj in oss2.ObjectIterator(bucket, prefix = 'ods/', delimiter = '/'):
	# 通过is_prefix方法判断obj是否为文件夹。
	if obj.is_prefix(): # 判断obj为文件夹。
		print('directory: ' + obj.key)
	else: # 判断obj为文件。
		print('file: ' + obj.key)
## > file: ods/
## > directory: ods/clicker/
## > directory: ods/snapshot/

for obj in oss2.ObjectIterator(bucket, prefix = '.', delimiter = '/'):
	# 通过is_prefix方法判断obj是否为文件夹。
	if obj.is_prefix(): # 判断obj为文件夹。
		print('directory: ' + obj.key)
	else: # 判断obj为文件。
		print('file: ' + obj.key)
##> directory: .dlsdata/

aaa = bucket.put_object('ods/novammp-emu/', '')

for obj in oss2.ObjectIterator(bucket, prefix = 'ods/', delimiter = '/'):
	# 通过is_prefix方法判断obj是否为文件夹。
	if obj.is_prefix(): # 判断obj为文件夹。
		print('directory: ' + obj.key)
	else: # 判断obj为文件。
		print('file: ' + obj.key)
##> file: ods/
##> directory: ods/clicker/
##> directory: ods/novammp-emu/
##> directory: ods/snapshot/