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的信息的话),我们可以对返回的对象再进行操作(比如删除,修改等)
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
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()
运行 python ceph_s3.py 执行结果:
[‘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
页面中上传,下载,测试通过。