为了账号安全,请及时绑定邮箱和手机立即绑定

OSS上传和下载学习笔记

标签:
Python

# -*- coding: utf-8 -*-

import oss2

from itertools import islice

import os

import datetime

from time import sleep


# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。

auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')

# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。

# yourBucketName填写存储空间名称。

bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')


# 读取txt文件内容

textdict = {}

configPath = r'.\filePath.txt'  # 这里是txt文本配置文件的路径,修改为你自己的

f = open(configPath, "r", encoding='utf-8')

k = f.readline().strip()

file_dir = f.readline().strip()  # 上传时使用的本地路径

oss_dir = f.readline().strip()  # 上传时使用的OSS路径


#===================================================================================

# def does_bucket_exist(bucket):

#     try:

#         bucket.get_bucket_info()

#     except oss2.exceptions.NoSuchBucket:

#         return False

#     except:

#         raise

#     return True


# # 判断指定的Bucket是否存在。返回值为true表示存在,返回值为false表示不存在。

# exist = does_bucket_exist(bucket)

# if exist:

#     print('bucket exist')

# else:

#     print('bucket not exist')

#===================================================================================

# # oss2.ObjectIterator用于遍历文件。

# for b in islice(oss2.ObjectIterator(bucket), 10):

#     print(b.key)

# 进入itoc-rpa根目录

# for object_info in oss2.ObjectIterator(bucket):

# 进入itoc-rpa根目录下指定文件夹

# for object_info in oss2.ObjectIterator(bucket,prefix="test/"):

#===================================================================================

# 在OSS创建文件夹,目录需以正斜线结尾

# bucket.put_object('test/22/', '')  

# 上传单个文件到OSS。

# bucket.put_object_from_file('ceshi.pdf', 'D://test1//wx//itoc//putFile//测试.pdf')

# 下载单个文件到本地

# bucket.get_object_to_file('yunjpg.jpg', 'D:/test1/wx/itoc/getFile/testjpg.jpg')

# # OSS复制文件到另一个目录

# src_bucket_name='itoc-rpa'

# src_object_name='test/测试.docx'

# dest_object_name='test1/测试.docx'

# result = bucket.copy_object(src_bucket_name, src_object_name, dest_object_name)

# # 查看拷贝返回状态。

# print('result :', result.status)

#==================================================================================


#从本地上传文件到OSS

def put_file():

    # file_dir='D:/test1/wx/OSS/putFile'

    # oss_dir='test1'

    for i in os.listdir(file_dir):

        # oss上传后的路径

        oss_path = f'{oss_dir}/{i}'

        # print(oss_path)

        # 本地文件路径

        file_path = f'{file_dir}/{i}'

        # print(file_path)

        # print(i)

        complete_file_name = os.path.join(file_dir, i)

        print('11:',file_dir)

        print('22:',complete_file_name)

        if os.path.isdir(complete_file_name):

            # print("这是文件夹:",complete_file_name)

            # continue

            # print(oss_path)

            # 判断oss目录是否存在,目录需以正斜线结尾

            exists = bucket.object_exists(oss_path+'/')

            print(exists)

            if exists:

                print("文件夹存在")

            else:

                print("文件夹不存在")

                #在OSS创建文件夹,目录需以正斜线结尾

                bucket.put_object(oss_path+'/', '')

                print("文件夹已创建")

                # print(oss_path)

        if os.path.isfile(complete_file_name):

            print("这是文件:",complete_file_name)

            # 上传文件

            bucket.put_object_from_file(oss_path, file_path)


#下载文件,获取文件最后修改时间

def get_file():

    gmt_time1='Thu, 30 Mar 2023 06:13:53 GMT'

    GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'

    b=datetime.datetime.strptime(gmt_time1, GMT_FORMAT) + datetime.timedelta(hours=8)

   

    # print(type(b))

    # print(timestamp)

    # 进入itoc-rpa根目录下指定文件夹

    while True:

        now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        now_times = datetime.datetime.strptime(now_time, "%Y-%m-%d %H:%M:%S")

        for object_info in oss2.ObjectIterator(bucket,prefix="test/"):

            # print(type(now_times))

            # print(object_info.key)

            simplifiedmeta = bucket.get_object_meta(object_info.key)

           

            #如果是文件夹则继续判断文件夹是否存在

            if object_info.key.endswith('/'):        

                continue

                # os_path='D:/test1/wx/OSS/getFile/'+object_info.key

                # print(os_path)

                # if os.path.exists(object_info.key):

                #     print('文件夹已存在')

                # else:

                #     print('文件夹不存在')

                #     #创建本地文件夹

                #     os.mkdir(os_path)

            # print(simplifiedmeta.headers['Content-Length'])

            # print(simplifiedmeta.headers['ETag'])

            # # 开启访问追踪功能后,用于获取包含最后一次访问时间(x-oss-last-access-time)在内的文件元信息。仅Python SDK 2.16.1及以上版本支持获取x-oss-last-access-time。

            # print(simplifiedmeta.headers['x-oss-last-access-time'])


            #获取文件最后修改时间

            gmt_time2=simplifiedmeta.headers['Last-Modified']

           

            # print(type(gmt_to_bjtime))

            # print(gmt_time2)

            # print(type(gmt_time2))

            # print('---------------')

            # print(gmt_time1)

            # GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'

            # #把获取的GMT时间转为北京时间

            a = datetime.datetime.strptime(gmt_time2, GMT_FORMAT) + datetime.timedelta(hours=8)

            # print(a)


            # 文件名:文件路径按照斜杠分割取最后一个

            file_name = object_info.key.split('/')[-1]

            # 下载到的具体路径

            save_dir = 'D:/test1/wx/OSS/getFile/test/'

            save_path = os.path.join(save_dir, file_name)

           

           

            # 若文件最后修改时间大于等于指定时间,则下载

            if a > b:

                print(object_info.key)

               

                # 从oss下载文件

                bucket.get_object_to_file(object_info.key, save_path)             

            else:

                continue

        print("fz")

        b=now_times

        print(b)

        sleep(20)


def main():

    put_file()

    get_file()


if __name__ == "__main__":

    main()


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消