博客
关于我
python调用aws api操作s3
阅读量:603 次
发布时间:2019-03-12

本文共 1729 字,大约阅读时间需要 5 分钟。

配置AWS环境并进行S3上传下载操作

创建配置文件夹

mkdir ~/.aws

生成密钥文件

请在用户的主目录下创建配置文件

vim ~/.aws/config

[default] 提供的输出格式为JSON

region = ap-northeast-2

默认区域设置

创建密钥文件

请在配置文件夹中创建或编辑密钥文件

vim ~/.aws/credentials

[default]

aws_access_key_id = AWS密钥ID

aws_secret_access_key = AWS秘密密钥

编写上传脚本

vim upload.py

以下是示例Python脚本

#!/usr/bin/pythonimport loggingimport boto3from botocore.exceptions import ClientErrordef upload_file(file_name, bucket, object_name=None):    """上传文件到S3桶    参数:        file_name: 需要上传的文件        bucket: 上传的S3桶名        object_name: S3对象名,默认与file_name相同    返回值:        True/False    """    if object_name is None:        object_name = file_name    s3_client = boto3.client('s3')    try:        response = s3_client.upload_file(file_name, bucket, object_name)    except ClientError as e:        logging.error(e)        return False    return Truedef main():    # 替换为实际值    bucket_name = 'test-bucket'    file_name = 'testfile'    object_name = 'testfile'        # 设置日志    logging.basicConfig(        level=logging.DEBUG,        format='%(levelname)s: %(asctime)s: %(message)s'    )        # 上传文件    response = upload_file(file_name, bucket_name, object_name)    if response:        logging.info('文件已上传')if __name__ == '__main__':    main()

下载操作示例

请根据实际需求编写下载脚本

vim download.py

#!/usr/bin/pythonimport boto3# 替换为实际值BUCKET_NAME = 'test-bucket'KEY = 'testfile'download_path = 'testfile's3 = boto3.resource('s3')try:    s3.Bucket(BUCKET_NAME).download_file(KEY, download_path)except botocore.exceptions.ClientError as e:    if e.response['Error']['Code'] == "404":        print("对象不存在.")    else:        raise

使用AWS CLI进行批量操作

# 上传示例aws s3 cp ./testfile s3://testbucket/testfile

# 下载示例aws s3 cp s3://testbucket/testfile ./

更多Python操作示例

请根据实际需求扩展脚本功能

转载地址:http://qabxz.baihongyu.com/

你可能感兴趣的文章
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>
Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
查看>>
nodejs libararies
查看>>
nodejs-mime类型
查看>>
nodejs中Express 路由统一设置缓存的小技巧
查看>>
Node入门之创建第一个HelloNode
查看>>