s3.Object()引发TypeError:序列项0:预期的str实例,找到了元组

时间:2019-02-24 19:07:22

标签: python amazon-s3 boto3

在boto3文档之后,我尝试这样做:

session = boto3.Session(
aws_access_key_id=KEY,
aws_secret_access_key=SECRET_KEY
)
s3 = session.resource('s3')

obj = s3.Object('test', 'test/myfile.csv')

当我运行obj.get()时,我收到:

  

TypeError:序列项0:预期的str实例,找到了元组

我需要获取此csv文件的内容。

当我使用客户端而不是会话尝试相同操作时,它将起作用:

s3 = boto3.client('s3')
obj = s3.get_object(Bucket='test', Key='test/myfile.csv')

1 个答案:

答案 0 :(得分:2)

此问题同时适用于AWS S3存储桶和DigitalOcean Spaces存储桶。

要复制错误:

import boto3

KEY = '********************',
SECRET_KEY = '*******************************************'

# Initialize a session using DigitalOcean Spaces.
session = boto3.session.Session()

client = session.client('s3', region_name='sgp1',
                        endpoint_url='https://sgp1.digitaloceanspaces.com',
                        aws_access_key_id=KEY,
                        aws_secret_access_key=SECRET_KEY)

引发错误:

~/.pyenv/versions/3.8.0/lib/python3.8/site-packages/botocore/auth.py in scope(self, request)
    322         scope.append(self._service_name)
    323         scope.append('aws4_request')
--> 324         return '/'.join(scope)
    325 
    326     def credential_scope(self, request):

TypeError: sequence item 0: expected str instance, tuple found

API似乎有问题,但是如果我们仔细看,

>>>print(type(SECRET_KEY))
str

>>> print(type(KEY))
tuple

michael-sqlbot所述,其中一个auth密钥中有一种tuple类型。

请注意上面的代码中的逗号:

import boto3

KEY = '********************',

只需删除逗号即可将其更改为字符串类型:

import boto3

KEY = '********************',
SECRET_KEY = '*******************************************'

# Initialize a session using DigitalOcean Spaces.
session = boto3.session.Session()

client = session.client('s3', region_name='sgp1',
                        endpoint_url='https://sgp1.digitaloceanspaces.com',
                        aws_access_key_id=KEY,
                        aws_secret_access_key=SECRET_KEY)

[输出]:

{'ResponseMetadata': {'RequestId': '*************',
  'HostId': '',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'transfer-encoding': 'chunked',
   'x-amz-request-id': '*************',
   'content-type': 'application/xml',
   'date': 'Mon, 15 Jun 2020 01:14:42 GMT',
   'strict-transport-security': 'max-age=15552000; includeSubDomains; preload'},
  'RetryAttempts': 0},
 'Buckets': [{'Name': '*****',
   'CreationDate': datetime.datetime(2019, 11, 20, 8, 28, 36, 548000, tzinfo=tzutc())}],
 'Owner': {'DisplayName': '*******', 'ID': '********'}}