天天看點

python通過boto3實作ceph s3分布式存儲上傳下載下傳功能前言環境支援開始結束

python通過boto3實作ceph S3分布式存儲上傳下載下傳功能

  • 前言
  • 環境支援
  • 開始
  • 結束

前言

aws是Amazon Web Service的簡寫,它包括衆多服務,其中最有名的兩個是EC2和S3。

S3是Simple Storage Service的簡寫,它是一種對象存儲的實作。

本文檔介紹使用者如何使用boto3來操作s3對象存儲服務。boto3提供了兩個級别的接口來通路AWS服務:

High Level的Resource級别的接口,Low Level的Client接口。

Client級别的接口傳回Dictionary來表示查詢到的資源資訊,Resource級别的接口對Client級别的接口進行了面向對象的封裝,接口的傳回值大部分都是Resource對象(如果傳回值是某個Resource的資訊的話),我們可以對傳回的對象再進行操作(比如删除,修改等)

環境支援

  • python版本:2.7
  • 通過pip安裝, pip install boto3 ,也可以安裝boto2

開始

  1. 建立叢集,建立s3使用者,建立存儲桶。這些操作不再講解,可以參考官方文檔。
  2. 老版本boto操作方式,直接上代碼
import boto
import boto.s3.connection
class CephS3():

    def __init__(self):
        access_key = '111111'
        secret_key = '11111'
        IP = '192.168.1.1'
        PORT = 7480
        self.conn = boto.connect_s3(
                aws_access_key_id=access_key,
                aws_secret_access_key=secret_key,
                host=IP,
                port=PORT,
                is_secure=False, # 不驗證ssl
                calling_format=boto.s3.connection.OrdinaryCallingFormat(),
        )

    def get_bucket(self):
		# 擷取存儲桶
        for bucket in self.conn.get_all_buckets():
                print "{name}\t{created}".format(
                        name = bucket.name,
                        created = bucket.creation_date,
                )

    def upload_file(self):
    	# 上傳
        bucket = self.conn.get_bucket('Aaa')
        key = bucket.new_key('hello.txt')
        key.set_contents_from_string('Hello World!')


    def download_file(self):
    	# 下載下傳
        bucket = self.conn.get_bucket('Aaa')
        hello_key = bucket.get_key('hello.txt')
        #key.get_contents_to_filename('/hello.txt')
        hello_url = hello_key.generate_url(0, query_auth=False, force_http=True)
        print hello_url
           
  1. 重點,官方推薦使用新版本boto3

    BOTO3官方文檔

from boto3.session import Session
# 新版本boto3

class CephS3BOTO3():

    def __init__(self):
        access_key = '111111'
        secret_key = '1111111'
        self.session = Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
        self.url = 'http://192.168.1.1:7480'
        self.s3_client = self.session.client('s3', endpoint_url=self.url)

    def get_bucket(self):
        buckets = [bucket['Name'] for bucket in self.s3_client.list_buckets()['Buckets']]
        print  buckets
        return buckets

    def create_bucket(self):
        # 預設是私有的桶
        self.s3_client.create_bucket(Bucket='hy_test')
        # 建立公開可讀的桶
        # ACL有如下幾種"private","public-read","public-read-write","authenticated-read"
        self.s3_client.create_bucket(Bucket='hy_test', ACL='public-read')

    def upload(self):
        resp = self.s3_client.put_object(
            Bucket="Aaa",# 存儲桶名稱
            Key='test', # 上傳到
            Body=open("/Users/xx/Desktop/test.txt", 'rb').read()
        )
        print resp
        return resp

    def download(self):
        resp = self.s3_client.get_object(
            Bucket='Aaa',
            Key='test'
        )
        with open('/Users/xx/Desktop/test_1.txt', 'wb') as f:
            f.write(resp['Body'].read())
if __name__ == "__main__":
    # boto3
    cephs3_boto3 = CephS3BOTO3()
    cephs3_boto3.get_bucket()
    cephs3_boto3.upload()
    cephs3_boto3.download()
           
  • 代碼中,access_key 與 secret_key 是在對象存儲服務中建立使用者後,在頁面上申請 到的給使用者用于通路對象存儲的認證資訊。而url是對象存儲服務提供的服務位址及端口。
  • 在初始化之後,就可以利用s3和s3_client進行各種操作了。
  • Session對象承載了使用者的認證資訊 session.client()對象用于服務相關的操作,目前就是用來列舉Bucket;
  • -s3_client.list_buckets()[‘Buckets’]對象是一個可以周遊使用者Bucket資訊的疊代器

運作 python ceph_s3.py 執行結果:

python通過boto3實作ceph s3分布式存儲上傳下載下傳功能前言環境支援開始結束

[‘Aaa’] 是存儲桶清單。

下面的是上傳成功傳回的資訊。

檢視下載下傳路徑,test_1.txt也下載下傳成功。

等等,上傳檔案時一般前端頁面傳的都是二進制流,那麼隻需要把Body修改為二進制流資料即可。

api接收
    file = request.FILES.get('file')
    傳參
    def upload(self, file):
       resp = self.s3_client.put_object(
           Bucket="Aaa",
           Key='test',
           Body = file
       )
       return resp
           

頁面中上傳,下載下傳,測試通過。

結束