溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python boto和boto3實現(xiàn)操作bucket的方法

發(fā)布時間:2020-11-02 15:58:49 來源:億速云 閱讀:151 作者:Leah 欄目:開發(fā)技術

本篇文章給大家分享的是有關python boto和boto3實現(xiàn)操作bucket的方法,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

boto操作

import datetime

import boto.s3.connection
from boto.s3.key import Key
conn = boto.connect_s3(
  aws_access_key_id="123456",
  aws_secret_access_key="123456",
  host="127.0.0.1",
  port=8080,
  is_secure=False,
  calling_format=boto.s3.connection.OrdinaryCallingFormat(),
)

str_bucket_name = "bucket_test"
conn.create_bucket(str_bucket_name) # 創(chuàng)建bucket

for bucket in conn.get_all_buckets(): # 獲取所有bucket
  # 將實際轉為本地時間
  print({"name": bucket.name, "create_date": str(datetime.datetime.strptime(bucket.creation_date, "%Y-%m-%dT%H:%M:%S.%fZ") + datetime.timedelta(hours=8))})


# 刪除指定的bucket
for bucket in conn.get_all_buckets():
  if bucket.name == str_bucket_name:
    for key in bucket.list(): # 必須將bucket里清空后,才能刪除掉對應的bucket
      bucket.delete_key(key.name)
    conn.delete_bucket(bucket.name)
    break

# 存儲文件流或字符串中的數(shù)據
key = Key('hello.txt')

key.set_contents_from_file('/tmp/hello.txt')

使用boto進行https的連接失敗,  validate_certs設置成True或False沒有任何作用

is_secure為Ture時,遇到的報錯如下

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1076)

is_secure為False時,遇到的報錯如下

http.client.RemoteDisconnected: Remote end closed connection without response

遂更換了botot3

boto3,下面的示例是用的https的(boto對于https的連接不上,可能是因為我的證書是自制的,所以才找了這個包)

import urllib3
import boto3

urllib3.disable_warnings()

s3 = boto3.resource(
  service_name='s3',
  aws_access_key_id="123456",
  aws_secret_access_key="123456",
  endpoint_url='https://192.168.150.20:8080',
  verify=False
)

str_bucket_name = "bucket_test"
s3.create_bucket(Bucket=str_bucket_name)


for bucket in s3.buckets.all(): # 獲取所有bucket
  # 將實際轉為本地時間
  print({"name": bucket.name, "create_date": datetime.datetime.strftime(bucket.creation_date + datetime.timedelta(hours=8), "%Y-%m-%d %H:%M:%S")})

# 刪除指定的bucket
for bucket in s3.buckets.all():
  if bucket.name == str_bucket_name:
    bucket.objects.all().delete()  # 等價于下面兩行
    # for obj in bucket.objects.all():
    #   obj.delete()
    bucket.delete()

# 存儲文件流或字符串中的數(shù)據
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))

以上就是python boto和boto3實現(xiàn)操作bucket的方法,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI