当前位置:   article > 正文

Python Amazon S3文件上传_s3 upload file

s3 upload file

        Amazon Simple Storage Service (Amazon S3) 是一种对象存储服务,提供行业领先的可扩展性、数据可用性、安全性和性能。这意味着各种规模和行业的客户都可以使用 S3 来存储并保护各种用例(如数据湖、网站、移动应用程序、备份和还原、存档、企业应用程序、IoT 设备和大数据分析)的数据,容量不限, S3 可达到 99.999999999%(11 个 9)的持久性.

 需求背景

        原amazon的s3上传比较繁琐,对于需要经常上传并且获取s3url的需求(国际产品开发常见)不太友好,因此希望使用代码上传

代码实现

关键信息可以自己登陆amonzon获取。地址为:

https://console.aws.amazon.com/iam/home?region=ap-east-1#/security_credentials

关于如何获取amazon的accesskey这里不详细介绍...

话不多说,代码如下:

  1. import os
  2. import datetime
  3. import bson
  4. import boto3
  5. def s3back(res):
  6. print("【aws回调函数】",res)
  7. def s3Upload(_path, _type):
  8. '''
  9. 上传指定文件到aws s3
  10. :param _path: 文件的绝对路径
  11. :param _type: 文件的content-type,例如image/png这种,可以通过filetype包获取
  12. :return: aws s3的url地址,可以直接访问并获取到文件
  13. '''
  14. #[获取地址](https://console.aws.amazon.com/iam/home?region=ap-east-1#/security_credentials)
  15. if not os.path.exists(_path): #文件不存在
  16. raise FileNotFoundError("this file not exists!")
  17. print("s3完整文件路径:%s, 文件类型类型:%s" % (_path, _type))
  18. AwsAccessKeyId = "AAAAAAAAAAAAAAAAAAAA" #【换成自己的】20位长度大写字母与数字的混合
  19. AwsSecretAccessKey = "00000000000000000000000000000000000000000000000000" #【换成自己的】40位长度大小写字母 + 特殊符号 + 数字的混合
  20. S3Region = "ap-southeast-1"
  21. S3Bucket = "webtest-ios-upload-pro"
  22. try:
  23. session = boto3.Session(
  24. aws_access_key_id = AwsAccessKeyId,
  25. aws_secret_access_key = AwsSecretAccessKey,
  26. region_name = S3Region
  27. )
  28. s3 = session.client("s3")
  29. #ACL参数可选: 'private'|'public-read'|'public-read-write'|'authenticated-read' (私有|公共读取|公共读写|认证读取 )
  30. extraData = {
  31. 'ACL': 'public-read',
  32. "ContentType": _type,
  33. "ServerSideEncryption":"AES256",
  34. "StorageClass": "INTELLIGENT_TIERING"
  35. }
  36. #bson.ObjectId() 创建一个24位的随机ID,类似UUID那种
  37. #key用于唯一标识aws s3存储桶中的文件,防止文件冲突,会使用uuid与时间的方式标识key。也可以自定义命名
  38. key = datetime.datetime.now().strftime("%Y%m%d") + "/" + str(bson.ObjectId()) + "." + _path.split(".")[-1]
  39. #upload没有返回结果,但可以通过回调函数,返回一个任务的ID
  40. s3.upload_file(Filename=_path, Bucket=S3Bucket, Key=key, ExtraArgs=extraData, Callback=s3back)
  41. uploadURL = "https://%s.s3.%s.amazonaws.com/%s" % (S3Bucket, S3Region, key)
  42. return uploadURL
  43. except Exception as e:
  44. raise e
  45. if __name__=="__main__":
  46. s3Upload("./test.png", "image/png")

方法源码

因为一开始也是参考网上的用例,和实际实现有些出入,比如s3.upload_file方法在pydoc与官网说明中都是extra_args参数,但实际运行会报错:

TypeError: upload_file() got an unexpected keyword argument 'extra_args'

然后通过help查看方法的源码,才发现这个参数实际是ExtraArgs。

  1. >>> help(s3.upload_file)
  2. Help on method upload_file in module boto3.s3.inject:
  3. upload_file(Filename, Bucket, Key, ExtraArgs=None, Callback=None, Config=None) method of botocore.client.S3 instance
  4. Upload a file to an S3 object.
  5. Usage::
  6. import boto3
  7. s3 = boto3.resource('s3')
  8. s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')
  9. Similar behavior as S3Transfer's upload_file() method,
  10. except that parameters are capitalized. Detailed examples can be found at
  11. :ref:`S3Transfer's Usage <ref_s3transfer_usage>`.
  12. :type Filename: str
  13. :param Filename: The path to the file to upload.
  14. :type Bucket: str
  15. :param Bucket: The name of the bucket to upload to.
  16. :type Key: str
  17. :param Key: The name of the key to upload to.
  18. :type ExtraArgs: dict
  19. :param ExtraArgs: Extra arguments that may be passed to the
  20. client operation.
  21. :type Callback: function
  22. :param Callback: A method which takes a number of bytes transferred to
  23. be periodically called during the upload.
  24. :type Config: boto3.s3.transfer.TransferConfig
  25. :param Config: The transfer configuration to be used when performing the
  26. transfer.

结果论证

如果accesskey等键值存在问题,代码运行会直接报错。报错信息比较友好,翻译基本能看懂。

其他问题:

Access denied

        与上传的权限有关,主要由ACL参数控制访问权限,如果登录的用户与上传的用户key不一致,可能导致访问拒绝。另外publiced-read是全部公开权限,所有人都可以访问

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/707220
推荐阅读
相关标签
  

闽ICP备14008679号