Python Boto - 将文件上传到 Amazon S3 上的特定位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14317243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:03:56  来源:igfitidea点击:

Boto - Uploading file to a specific location on Amazon S3

pythonamazon-web-servicesamazon-s3boto

提问by Jimmy

This is the code I'm working from

这是我正在使用的代码

import sys
import boto
import boto.s3

# AWS ACCESS DETAILS
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''

bucket_name = AWS_ACCESS_KEY_ID.lower() + '-mah-bucket' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT)
uploadfile = sys.argv[1]

print 'Uploading %s to Amazon S3 bucket %s' % \
       (uploadfile, bucket_name)

def percent_cb(complete, total):
    sys.stdout.write('.')
    sys.stdout.flush()

from boto.s3.key import Key
k = Key(bucket)
k.key = 'my test file'
k.set_contents_from_filename(testfile, cb=percent_cb, num_cb=10)

On my S3 I have created "directories", like this "bucket/images/holiday". I know these are only virtual directories.

在我的 S3 上,我创建了“目录”,例如“bucket/images/holiday”。我知道这些只是虚拟目录。

My question is, how can I modify this upload specifically to bucket/images/holiday virtual directory on S3 rather than the bucket root?

我的问题是,如何专门将此上传修改为 S3 上的存储桶/图像/假日虚拟目录而不是存储桶根目录?

采纳答案by garnaat

All you should have to do is prepend the virtual directory path to the key name prior to uploading. For example:

您所要做的就是在上传之前将虚拟目录路径添加到密钥名称之前。例如:

key_name = 'my test file'
path = 'images/holiday'
full_key_name = os.path.join(path, key_name)
k = bucket.new_key(full_key_name)
k.set_contents_from_filename(...)

You may have to change that a bit for your application but hopefully that gives you the basic idea.

您可能需要为您的应用程序稍微更改它,但希望这可以为您提供基本的想法。

回答by olekb

You can also use this:

你也可以使用这个:

from boto.s3.key import Key

bucket = conn.get_bucket('images')
k = Key(bucket)
k.key = 'holiday/my_test_file.txt'

It works like this in my s3_percent_uploader

它在我的s3_percent_uploader 中是这样工作的

python.exe s3_percent_uploader.py test_upload.txt testbucket test/upload.txt

after upload file will be in testbucket/test/upload.txt

上传文件后将在 testbucket/test/upload.txt