本文主要是分享自己所用来文件上传到阿里云上的应用,是自己的一点简单代码的分享,供自己以后学习用。
首先是安装:https://help.aliyun.com/document_detail/31947.html?spm=a2c4g.11186623.4.2.fksCNQ
这里直接推荐阿里云的安装手册,非常齐全。这里笔者直接采用的是pip安装在这里就不进行分享了。
文件的一些简单应用,这里笔者不讲为什么直接上代码,因为是方便以后自己以后用,其他人仅供参考:
self.auth = oss2.Auth('自己的账号', '自己密码')
self.bucket = oss2.Bucket(self.auth, 'http://oss-cn-shanghai.aliyuncs.com/',
'自己云上的文件夹,需要自己创建')
一:判断文件是否存在
def exists(self, yourObjectName):
"""
判断文件是否存在
:param yourObjectName: 线上文件名称
:return: True or False
"""
try:
exist = self.bucket.object_exists(yourObjectName)
if exist:
user_input = raw_input('%s 文件已存在,y(覆盖),n(跳过):' % yourObjectName)
return True if user_input.lower() == 'y' else False
except BaseException as e:
# self.initLogging(yourObjectName)
raise BaseException("exists file: %s error %s" % (yourObjectName, e))
else:
return True
二:上传文件
def put_file(self, yourObjectName, yourLocalFile):
"""
上传文件
:param yourObjectName: 线上文件名称
:param yourLocalFile: 本地文件名称
:return: True or False
"""
is_write = self.exists(yourObjectName)
# self.bucket.put_object_from_file('hahah\66.txt', 'C:\Users\Dell\Desktop\66.txt')
if is_write:
try:
result = self.bucket.put_object_from_file(yourObjectName, yourLocalFile)
except Exception as e:
print(u'上传错误,%s' % e)
else:
if result.status == 200:
print '%s upto %s sucess' % (yourLocalFile, yourObjectName)
else:
print result.status
三:以字节的方式进行上传文件
def put_content_file(self, yourObjectName, content):
"""
以字节的方式进行上传文件
:param yourObjectName: 线上文件名称
:param content: b'content of object'
:return: True or False
"""
is_write = self.exists(yourObjectName)
# self.bucket.put_object_from_file('zhongdeng\66.txt', 'C:\Users\Dell\Desktop\66.txt')
if is_write:
try:
result = self.bucket.put_object(yourObjectName, content)
except Exception as e:
return u'%s upload faild,%s' %(yourObjectName, e)
else:
if result.status == 200:
return u'upload %s sucess' % yourObjectName
else:
return u'%s upload faild,%s' % (yourObjectName, str(result.status))
四:下载文件
def get_file(self,yourObjectName,yourLocalFile):
"""
下载文件
:param yourObjectName: 线上文件名称
:param yourLocalFile: 本地文件名称
:return: True or False
"""
self.bucket.get_object_to_file(yourObjectName, yourLocalFile)
五:列举文件
def list_file(self):
"""
列举文件
:return: True or False
"""
for obj in oss2.ObjectIterator(self.bucket, prefix='hahh.pdf'):
print(obj.key)
六:删除单个文件
def delete_one_file(self):
"""
删除单个文件
:return: True or False
"""
result = self.bucket.delete_object('66/hahh.pdf')
七:批量删除3个文件。每次最多删除1000个文件
def delete_more_file(self,yourObjectName):
"""
批量删除3个文件。每次最多删除1000个文件
:param yourObjectName: 线上文件名称
:return: True or False
"""
result = self.bucket.batch_delete_objects(['<yourObjectName-a>', '<yourObjectName-b>', '<yourObjectName-c>'])
# 打印成功删除的文件名。
print('\n'.join(result.deleted_keys))
八:配置日志,当然这个也是参考网上的,网上东西特别多。直接拿大佬的用即可,看到我参考的出处不要找我麻烦,我忘了我参考的是谁的了。尴尬
def initLogging(message):
filename = time.strftime('%Y-%m-%d', time.localtime(time.time())) + ' ' + str(time.time())
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename="./log/%s" % filename + ".log",
filemode='w')
# 添加StreamHandler在控制台也打印出来
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s -LINE %(lineno)-4d: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logging.info(message)
九:循环查找文件,上传所有的文件
def main():
rootdir = 'F:\pdfs'
for root, dirs, list_file in os.walk(rootdir): # root 当前目录路径; dirs 当前路径下所有子目录 ;files 当前路径下所有非目录子文件
pdf_list = [_i for _i in list_file if _i.endswith('.pdf')]
for index, fname in enumerate(pdf_list, 1):
path = os.path.join(root, fname)
if os.path.isfile(path):
print ("start upload %s to_file: %s" % (path, fname))
云上文件夹.put_file('66/'+fname, path)
当然所有的参考都是参考阿里云大佬所写的,连接地址如下:
https://help.aliyun.com/document_detail/32027.html?spm=a2c4g.11186623.2.11.2lzWsW。