AWS Lambda中解压S3文件时的文件名问题(使用Python)

3
我有如下的lambda函数:
from __future__ import print_function

import urllib
import zipfile
import boto3
import io
import mimetypes

import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)


s3 = boto3.client('s3')
bucket = 'staging-bucket'

def lambda_handler(event, context):
    try:
        key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
        obj = s3.get_object(Bucket=bucket, Key=key)
        with io.BytesIO(obj["Body"].read()) as tf:
            # rewind the file
            tf.seek(0)
            # Read the file as a zipfile and process the members
            with zipfile.ZipFile(tf, mode = 'r') as zipf:
                for file in zipf.infolist():
                    fileName = file.filename
                    contentType, encoding = mimetypes.guess_type(fileName)
                    contentType = contentType or 'application/octet-stream'
                    filePath = "playable/staging/" + key.replace("package.zip", "") + fileName
                    putFile = s3.put_object(ACL = 'public-read', Bucket = "unzipped-bucket", Key = filePath, Body = zipf.read(file), ContentType = contentType)


    except Exception as e:
        logger.error('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e

    return

该函数从s3存储桶中获取zip文件并将其提取到另一个s3存储桶中。

该函数成功运行,但提取的文件名具有zip文件名作为前缀,参见下面的图片。

源zip文件:package-1542108930.zip

源zip文件内容: source zip files

提取的文件夹内容: extracted files

我无法在Python脚本中找到错误,非常感谢您的帮助。

1个回答

1
我猜测你的问题在于这一行:


filePath = "playable/staging/" + key.replace("package.zip", "") + fileName

请注意,您正在删除字符串package.zip,但是(从“前缀”中可以看出),实际上该字符串是package-1542108930.zip
尝试使用以下代码:
filePath = "playable/staging/" + fileName

如果您不想要任何名称。

如果您想要保留时间戳,则:

filePath = "playable/staging/" + key.replace("package-", "").replace(".zip", "") + fileName

你的代码只适用于一个zip文件,问题在于每个zip文件都有不同的名称(时间戳)。 - Jaydev Shiroya
是的-你必须以编程方式创建正确的替换字符串;但你遇到这个问题的原因是因为你当前的“package.zip”字符串与你需要替换的不匹配。从你的问题中没有足够的上下文让我知道你如何做到这一点,但我会从S3事件中猜测一下。 - thomasmichaelwallace
如果这仍然不是您想要的,请提供正确路径的示例。 - thomasmichaelwallace
使用您的代码 filePath = "playable/staging/" + fileName ,无法将zip文件解压缩。 - Jaydev Shiroya
我有许多不同时间戳的package-{timestamp}.zip文件,我想将它们的内容提取到不同的bucket中。 - Jaydev Shiroya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接