繁体   English   中英

将文件上传到 Python 中的 AWS S3 存储桶文件夹会导致正则表达式错误

[英]Uploading Files to AWS S3 Bucket Folder in Python Causes Regex Error

我有一个名为task-details的 AWS S3 存储桶和一个名为archive的文件夹,因此 S3 URI 是s3://task-details/archive/arn:aws:s3:::task-details/archive/ ARN。 我正在尝试使用 Python 的 boto3 package 中的upload_file方法将 CSV 文件上传到 S3 存储桶中的文件夹。

以下是我用来尝试将数据上传到文件夹的方法,但我不断收到正则表达式错误,这让我认为我无法将数据上传到存储桶中的特定文件夹。 有谁知道如何做到这一点?

方法:

import logging
import boto3
from botocore.exceptions import ClientError

def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # Upload the file
    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 True

我的代码(我也试过bucket = s3://task-details/archive/bucket = task-details/archive/ ):

upload_file(
    file_name = filepath, 
    bucket = "arn:aws:s3:::task-details/archive/", 
    object_name = object_name
)

错误:

Invalid bucket name "arn:aws:s3:::task-details/archive/": Bucket name must match the regex 
"^[a-zA-Z0-9.\-_]{1,255}$" or be an ARN matching the regex "^arn:(aws).*:(s3|s3-object-lambda):[a-z\-0-9]+:[0-9]{12}:accesspoint[/:][a-zA-Z0-9\-]{1,63}$|^arn:(aws).*:s3-outposts:[a-z\-0-9]+:[0-9]{12}:outpost[/:][a-zA-Z0-9\-]{1,63}[/:]accesspoint[/:][a-zA-Z0-9\-]{1,63}$"

API 调用需要存储桶名称或 ARN。 您的存储桶名称是task-details并且您的存储桶 ARN 是arn:aws:s3:::task-details

您在调用upload_file时使用 Key 参数来指定对象的键,例如archive/cats/persian.png 请注意,S3 object 键不仅仅是对象/文件名,还包括前缀/文件夹。

问题是我需要将文件夹路径添加为object_name而不是bucket的一部分。

固定代码:

upload_file(
    file_name = filepath, 
    bucket = "arn:aws:s3:::task-details", 
    object_name = "archive/" + object_name
)

就我而言,其他答案没有解决错误。 我不得不将存储桶名称从 arn(“arn:aws:s3:::bucket-name”)更改为单独的存储桶名称(“bucket-name”)。

我试图上传 zip 文件的内容。 我还想上传到存储桶内的文件夹。 所以这是我的工作解决方案。

s3.upload_fileobj(
       Bucket='user-data',
       Key='my_extracted-files/' + file_name, # file_name is the name of file
       Fileobj=zop # This is a file obj
      )

我的猜测是bucket的命名格式和key params对于方法是一样的:upload_file too

注意:不要忘记在您的策略中添加 Put 权限

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM