本文介绍了将对象放入boto3的存储桶中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#!/usr/bin/env python3
import sys
import boto3
s3 = boto3.resource("s3")
bucket_name = sys.argv[1]
object_name = sys.argv[2]
try:
response = s3.Object(bucket_name,
object_name).put(Body=open(object_name, 'rb'))
print (response)
except Exception as error:
print (error)
这是我的put_bucket函数,它将对象放入存储桶,但是一旦我调用主程序(基本上是自动的),我几乎不需要用户输入就可以完成它.
That's my put_bucket function that puts objects into buckets but I need it done with little to no user input once I call the main program, basically automatic.
import sys
import boto3
ec2 = boto3.resource('ec2', region_name = 'eu-west-1')
s3 = boto3.resource('s3')
keyname = 'AlexBpem.pem'
user_data = '''#!/bin/bash
yum update -y
yum install httpd -y
systemctl enable httpd
systemctl start httpd'''
s3.create_bucket(Bucket='ec2-assignbuke2',CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'})
sg = ec2.create_security_group(GroupName='MyWebServer', Description = 'WebServer', VpcId='vpc-0dea879f34afff60d')
instance = ec2.create_instances(
ImageId='ami-0fc970315c2d38f01',
MinCount=1,
MaxCount=1,
InstanceType='t2.nano',
KeyName = 'AlexBpem',
UserData = user_data,
SecurityGroupIds=[ sg.group_id ],
SubnetId = 'subnet-06add059500af7905'
)
for bucket_name in sys.argv[1:]:
try:
response = s3.create_bucket(Bucket=ec2-assignbuke2,
CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'})
print (response)
except Exception as error:
print (error)
是我的主程序,我将如何使用代码中的(def)函数使此调用自动进行.
Is my main program, how would I go abouts using (def) functions within my code to make this call automatic.
推荐答案
要将内联的上载到S3"代码转换为函数,可以执行以下操作:
To convert your inline 'upload to S3' code into a function, you can do this:
#!/usr/bin/env python3
import sys
import boto3
s3 = boto3.resource("s3")
def upload_to_s3(filename, bucket, key):
try:
response = s3.Object(bucket, key).put(Body=open(filename, 'rb'))
print (response)
return response
except Exception as error:
print (error)
要调用此功能,您可以执行以下操作:
To call this function, you can do this:
file = '/home/users/james/dogs/toto.png'
bkt = 'mybucket'
key = 'dogs/tot.png'
rsp = upload_to_s3(file, bkt, key)
这篇关于将对象放入boto3的存储桶中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!