【问题标题】:Download S3 Files with Boto使用 Boto 下载 S3 文件
【发布时间】:2016-09-23 08:54:32
【问题描述】:

我正在尝试设置一个应用程序,用户可以在其中下载存储在 S3 存储桶中的文件。我能够设置我的存储桶,并获得正确的文件,但它不会下载,给我这个错误:No such file or directory: 'media/user_1/imageName.jpg' 知道为什么吗?这似乎是一个相对简单的问题,但我似乎不太明白。我可以正确删除图像,因此它能够识别正确的图像。

这是我的意见.py

def download(request, project_id=None):
    conn = S3Connection('AWS_BUCKET_KEY', 'AWS_SECRET_KEY')
    b = Bucket(conn, 'BUCKET_NAME')
    k = Key(b)
    instance = get_object_or_404(Project, id=project_id)
    k.key = 'media/'+str(instance.image)
    k.get_contents_to_filename(str(k.key))
    return redirect("/dashboard/")

【问题讨论】:

  • 快速提示:由于您使用的是 django,您可以使用 django-storages 会更容易
  • 也许你应该使用 boto3 下载文件

标签: python amazon-web-services amazon-s3 boto


【解决方案1】:

问题是您正在下载到一个不存在的本地目录 (media/user1)。您需要:

  • 先在本地机器上创建目录
  • 只使用文件名而不是完整路径
  • 使用完整路径,但将斜杠 (/) 替换为另一个字符 - 这将确保文件名的唯一性,而无需创建目录

最后一个选项可以通过以下方式实现:

k.get_contents_to_filename(str(k.key).replace('/', '_'))

另请参阅:Boto3 to download all files from a S3 Bucket

【讨论】:

  • 你能不能给我一个简单的例子。我对 Boto 和 AWS 比较陌生。如果没有,那很好。
  • 这个答案应该有更多的赞成票。最简单的解决方案
  • 您可以使用os.makedirs()创建一个目录,如果需要,包括它的父目录。
【解决方案2】:

使用 boto3 下载文件非常简单,在使用此代码之前在系统级别配置您的 AWS 凭证。

client = boto3.client('s3')

// if your bucket name is mybucket and the file path is test/abc.txt
// then the Bucket='mybucket' Prefix='test'

resp = client.list_objects_v2(Bucket="<your bucket name>", Prefix="<prefix of the s3 folder>") 

for obj in resp['Contents']:
    key = obj['Key']
    //to read s3 file contents as String
    response = client.get_object(Bucket="<your bucket name>",
                         Key=key)
    print(response['Body'].read().decode('utf-8'))

    //to download the file to local
    client.download_file('<your bucket name>', key, key.replace('test',''))

replace是用s3文件名在本地定位文件,如果不替换会尝试另存为'test/abc.txt'。

【讨论】:

  • 这很有帮助,但 Python 代码中的 C 风格 cmets 令人不安。
【解决方案3】:
import os
import boto3
import json

s3 = boto3.resource('s3', aws_access_key_id="AKIAxxxxxxxxxxxxJWB",
                    aws_secret_access_key="LV0+vsaxxxxxxxxxxxxxxxxxxxxxry0/LjxZkN")
my_bucket = s3.Bucket('s3testing')

# download file into current directory
for s3_object in my_bucket.objects.all():
    # Need to split s3_object.key into path and file name, else it will give error file not found.
    path, filename = os.path.split(s3_object.key)
    my_bucket.download_file(s3_object.key, filename)

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 2020-01-03
    • 2012-08-31
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多