本文介紹如何快速使用OSS Python SDK完成常見操作,如創建存儲空間(Bucket)、上傳文件(Object)、下載文件等。
前提條件
配置憑證
使用RAM用戶AccessKey配置環境變量。
Linux
在命令行界面執行以下命令來將環境變量設置追加到
~/.bashrc
文件中。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
執行以下命令使變更生效。
source ~/.bashrc
執行以下命令檢查環境變量是否生效。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
在終端中執行以下命令,查看默認Shell類型。
echo $SHELL
根據默認Shell類型進行操作。
Zsh
執行以下命令來將環境變量設置追加到
~/.zshrc
文件中。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
執行以下命令使變更生效。
source ~/.zshrc
執行以下命令檢查環境變量是否生效。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
執行以下命令來將環境變量設置追加到
~/.bash_profile
文件中。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
執行以下命令使變更生效。
source ~/.bash_profile
執行以下命令檢查環境變量是否生效。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
在CMD中運行以下命令。
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
運行以下命令,檢查環境變量是否生效。
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
在PowerShell中運行以下命令。
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
運行以下命令,檢查環境變量是否生效。
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
安裝SDK
已安裝合適版本的Python運行環境,通過以下命令查看Python版本。
OSS Python SDK適用于Python 2.6、2.7、3.3、3.4、3.5、3.6、3.7、3.8及以上版本。
python -version
如果當前計算環境沒有安裝Python運行環境,請下載安裝Python。
安裝OSS Python SDK。
執行以下命令安裝SDK。
pip install oss2
運行示例
運行以下代碼示例以體驗OSS的完整使用流程:創建一個Bucket、上傳文件、下載文件、列舉文件以及刪除文件和Bucket。
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice
import os
import logging
import time
import random
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# 檢查環境變量是否已設置
required_env_vars = ['OSS_ACCESS_KEY_ID', 'OSS_ACCESS_KEY_SECRET']
for var in required_env_vars:
if var not in os.environ:
logging.error(f"Environment variable {var} is not set.")
exit(1)
# 從環境變量中獲取訪問憑證
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# 設置Endpoint和Region
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
def generate_unique_bucket_name():
# 獲取當前時間戳
timestamp = int(time.time())
# 生成0到9999之間的隨機數
random_number = random.randint(0, 9999)
# 構建唯一的Bucket名稱
bucket_name = f"demo-{timestamp}-{random_number}"
return bucket_name
# 生成唯一的Bucket名稱
bucket_name = generate_unique_bucket_name()
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
def create_bucket(bucket):
try:
bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE)
logging.info("Bucket created successfully")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to create bucket: {e}")
def upload_file(bucket, object_name, data):
try:
result = bucket.put_object(object_name, data)
logging.info(f"File uploaded successfully, status code: {result.status}")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to upload file: {e}")
def download_file(bucket, object_name):
try:
file_obj = bucket.get_object(object_name)
content = file_obj.read().decode('utf-8')
logging.info("File content:")
logging.info(content)
return content
except oss2.exceptions.OssError as e:
logging.error(f"Failed to download file: {e}")
def list_objects(bucket):
try:
objects = list(islice(oss2.ObjectIterator(bucket), 10))
for obj in objects:
logging.info(obj.key)
except oss2.exceptions.OssError as e:
logging.error(f"Failed to list objects: {e}")
def delete_objects(bucket):
try:
objects = list(islice(oss2.ObjectIterator(bucket), 100))
if objects:
for obj in objects:
bucket.delete_object(obj.key)
logging.info(f"Deleted object: {obj.key}")
else:
logging.info("No objects to delete")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to delete objects: {e}")
def delete_bucket(bucket):
try:
bucket.delete_bucket()
logging.info("Bucket deleted successfully")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to delete bucket: {e}")
# 主流程
if __name__ == '__main__':
# 1. 創建Bucket
create_bucket(bucket)
# 2. 上傳文件
upload_file(bucket, 'test-string-file', b'Hello OSS, this is a test string.')
# 3. 下載文件
download_file(bucket, 'test-string-file')
# 4. 列出Bucket中的對象
list_objects(bucket)
# 5. 刪除Bucket中的對象
delete_objects(bucket)
# 6. 刪除Bucket
delete_bucket(bucket)
文檔內容是否對您有幫助?