2017-02-22 64 views
0

鬥錯誤我用下面的代碼來檢查桶的存在:S3 API創建SOFTLAYER

def check_bucket_existed(bucket_name, public_auth_endpoint): 

    endpoint = 'https://' + public_auth_endpoint 
    s3 = boto3.resource('s3', endpoint_url=endpoint) 

    try: 
     s3.meta.client.head_bucket(Bucket=bucket_name) 
     exists = True 
    except botocore.exceptions.ClientError as e: 
     error_code = int(e.response['Error']['Code']) 
     if error_code == 404: 
      exists = False 
     else: 
      exists = True 
    return exists 

如果桶不存在,然後開始用下面的代碼創建鬥:

def create_bucket(bucket_name, public_auth_endpoint): 
    endpoint = 'https://' + public_auth_endpoint 
    s3 = boto3.resource('s3', endpoint_url=endpoint) 

    if check_bucket_existed(bucket_name, public_auth_endpoint): 
     print("Bucket {} existed , skip bucket creation process".format(bucket_name)) 
     return True 
    else: 
     print("Bucket {} doesn't exist, start bucket creation process.".format(bucket_name)) 
     try: 
      s3.create_bucket(Bucket=bucket_name) 
      if check_bucket_existed(bucket_name, public_auth_endpoint): 
       print("Bucket {} created successsfully.".format(bucket_name)) 
       return True 
     except botocore.exceptions.ClientError as e: 
      print("Error: Unable to create the bucket : %s" % e) 
      return False 

我對以下日誌迷茫運行create_bucket代碼時,得到:

Bucket td.cos.s1 doesn't exist, start bucket creation process. 
Error: Unable to create the bucket : An error occurred (BucketAlreadyExists) when calling the CreateBucket operation: The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again. 

在日誌中,首先它翔要使用的ws桶名稱不存在,但是當開始使用該名稱創建桶時,會提示ERROR信息顯示此桶名稱無法使用。

我多次使用此存儲桶名稱,並且可以使用此存儲桶名稱。

我的代碼有什麼問題?謝謝!

+0

這桶名稱前使用。但在運行此create_bucket代碼之前它已被刪除。 – Hengguo

回答

0

例外:

「的請求鬥名稱不可用桶命名空間是 通過該系統的所有用戶共享請選擇一個不同的名稱和 再試一次。」

存儲桶是唯一的,所以這意味着另一個客戶(可以來自其他帳戶)已經創建了一個與您嘗試的名稱相同的存儲桶。所以我建議用不同的名稱


更新的創建桶

你的腳本能正常工作,我必須成功創建鬥:td.cos.s1(我已經刪除了,爲您的測試)。你可以做雙重檢查嗎?

在這裏,我得到的結果:

False 
Bucket td.cos.s1 doesn't exist, start bucket creation process. 
Bucket td.cos.s1 created successsfully. 
True 
+0

但是通過check_bucket_existed方法,它顯示具有該名稱的存儲桶不存在。如何解釋這一點? – Hengguo

+0

我的歉意,我已經驗證你的腳本,請查看我的回答中的** Updated **部分 –

+0

在循環中運行以下代碼10次時發生此問題:1。創建雲對象存儲。 2.創建桶。 3.刪除桶。 4.刪除雲對象存儲。然後會有幾次這個問題發生。 – Hengguo