我有一个特定的用例,我想以特定的前缀将对象上传到 S3。该前缀处已经存在一个文件,我想用这个新文件替换该文件。我正在使用 boto3 来做同样的事情,但出现以下错误。存储桶版本控制已关闭,因此我希望在这种情况下覆盖文件。但是,我收到以下错误。
{
"errorMessage": "An error occurred (InvalidRequest) when calling the CopyObject operation: This copy request is illegal because it is trying to copy an object to itself without changing the object's metadata, storage class, website redirect location or encryption attributes.",
"errorType": "ClientError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 25, in lambda_handler\n s3.Object(bucket,product_key).copy_from(CopySource=bucket + '/' + product_key)\n",
" File \"/var/runtime/boto3/resources/factory.py\", line 520, in do_action\n response = action(self, *args, **kwargs)\n",
" File \"/var/runtime/boto3/resources/action.py\", line 83, in __call__\n response = getattr(parent.meta.client, operation_name)(*args, **params)\n",
" File \"/var/runtime/botocore/client.py\", line 386, in _api_call\n return self._make_api_call(operation_name, kwargs)\n",
" File \"/var/runtime/botocore/client.py\", line 705, in _make_api_call\n raise error_class(parsed_response, operation_name)\n"
]
}
这是我到目前为止所尝试的。
import boto3
import tempfile
import os
import tempfile
print('Loading function')
s3 = boto3.resource('s3')
glue = boto3.client('glue')
bucket='my-bucket'
bucket_prefix='my-prefix'
def lambda_handler(_event, _context):
my_bucket = s3.Bucket(bucket)
# Code to find the object name. There is going to be only one file.
for object_summary in my_bucket.objects.filter(Prefix=bucket_prefix):
product_key= object_summary.key
print(product_key)
#Using product_key variable I am trying to copy the same file name to the same location, which is when I get an error.
s3.Object(bucket,product_key).copy_from(CopySource=bucket + '/' + product_key)
# Maybe the following line is not required
s3.Object(bucket,bucket_prefix).delete()
我有一个非常具体的原因在同一位置复制同一个文件。AWS GLue 将其添加为书签后不会选择相同的文件。我再次复制文件我希望 Glue 书签将被删除,并且 Glue 作业会将其视为一个新文件。
我并不太关注这个名字。如果你能帮我修改上面的代码以生成一个同样有效的前缀级别的新文件。但是这里总是必须有一个文件。将此文件视为已从关系数据库购买到 S3 的产品的静态列表。
谢谢
对于 Amazon S3 输入源,AWS Glue 作业书签会检查对象的上次修改时间,以验证哪些对象需要重新处理。如果您的输入源数据自上次运行作业以来已被修改,则在您再次运行作业时会重新处理这些文件。
所以,看来你的理论可行!
但是,正如错误消息所述,“在不更改对象的元数据、存储类别、网站重定向位置或加密属性的情况下”,不允许将 S3 对象复制到自身。
因此,您可以添加一些元数据作为复制过程的一部分,它会成功。例如:
s3.Object(bucket,product_key).copy_from(CopySource=bucket + '/' + product_key, Metadata={'foo': 'bar'})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句