博客
关于我
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/

你可能感兴趣的文章
Nginx代理静态资源(gis瓦片图片)实现非固定ip的url适配网络环境映射ip下的资源请求解决方案
查看>>
Nginx反向代理与正向代理配置
查看>>
Nginx反向代理是什么意思?如何配置Nginx反向代理?
查看>>
nginx反向代理解决跨域问题,使本地调试更方便
查看>>
nginx启动脚本
查看>>
Nginx在Windows下载安装启动与配置前后端请求代理
查看>>
Nginx多域名,多证书,多服务配置,实用版
查看>>
nginx开机启动脚本
查看>>
nginx异常:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf
查看>>
nginx总结及使用Docker创建nginx教程
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
查看>>
nginx日志分割并定期删除
查看>>
Nginx日志分析系统---ElasticStack(ELK)工作笔记001
查看>>
Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
查看>>
nginx最最最详细教程来了
查看>>
Nginx服务器---正向代理
查看>>
Nginx服务器上安装SSL证书
查看>>
Nginx服务器的安装
查看>>
Nginx模块 ngx_http_limit_conn_module 限制连接数
查看>>