亚马逊云aws提供了s3服务。国内一些云厂商也用了s3技术。要操作s3服务器中的文件需要用到boto这个python包。下面的代码是一个简单例子。

#! /usr/bin/python
# -*-coding:utf-8-*


from boto.s3.key import Key
from boto.s3.connection import S3Connection
import os

########################################################################
user = "xxxxx"
aws_access_key_id = "xxxxxxxxxxxx"
aws_secret_access_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
host_ip = "114.114.114.114"
port=114
########################################################################



'''
OrdinaryCallingFormat:自己安装有s3服务的服务器一般用这个
SubdomainCallingFormat:host名中含有amazon类似的词语的一般用这个
'''
class S3(object):
   def __init__(self, ):

        self.conn = S3Connection(
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key,
            host=host_ip,
            port=port,
            is_secure=False,
            calling_format='boto.s3.connection.OrdinaryCallingFormat'
        )

        self.bucket_name = 'bucket_xxxx'
        try:
            self.bucket = self.conn.get_bucket(self.bucket_name)
        except:
            self.bucket = self.conn.create_bucket(self.bucket_name)

    def upload_packetage(self, package_path):
        package_name = os.path.basename(package_path)
        package_key = Key(self.bucket, package_name)
        if package_key.exists():
            package_key.delete()
        else:
            packege_key.set_contents_from_filename(package_path)
        return

    def rename_package(self, package_old_name, package_new_name):
        package_old_key = Key(self.bucket, package_old_name)
        package_new_key = Key(self.bucket, package_new_name)
        if package_old_key.exists() and (not package_new_key.exists()):
            package_old_key.copy(self.bucket, package_new_key)
        if  package_new_key.exists():
            package_old_key.delete()
        return

    def delete_packetage(self, package_name):
        package_key = Key(self.bucket, package_name)
        if package_key.exists():
            package_key.delete()
        else:
            raise ValueError('package:%s are not exist' % package_name)
        return

if __name__ == "__main__":
    #S3().upload_package("/home/text.txt")
    #S3().delete_package("text.txt")
    #S3().rename_package("text.txt", "text1.txt")
    pass
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐