[英]How to make my Object Image within my S3 Bucket Public in Python?
I'm trying to set my Object I have in my S3 Bucket to Public which I can do manually by selecting 'Make Public' option which allows 'Read' access within the Object ACL which works fine since it displays the image on my webpage fine, my question is what python code would I have to use to allow this 'Read' access within the ACL to allow my image to be public?我正在尝试将我在 S3 存储桶中的对象设置为公开,我可以通过选择“公开”选项手动执行该选项,该选项允许对象 ACL 中的“读取”访问,因为它可以在我的网页上正常显示图像,我的问题是我必须使用什么 python 代码来允许在 ACL 中进行这种“读取”访问以允许我的图像公开?
I have tried generating a policy which didn't work, I set the whole bucket to public which still didn't allow the image to be public aswell.我曾尝试生成一个不起作用的策略,我将整个存储桶设置为 public,但仍然不允许图像公开。 So unsure what Python code would allow this.
所以不确定什么 Python 代码会允许这样做。
#!/usr/bin/env python3
import sys
import boto3
ec2 = boto3.resource('ec2', region_name = 'eu-west-1')
s3 = boto3.resource('s3')
keyname = 'key2.pem'
user_data = '''#!/bin/bash
yum update -y
yum install httpd -y
systemctl enable httpd
systemctl start httpd'''
s3.create_bucket(ACL='private',Bucket='ec2-buket1',CreateBucketConfiguration={'$
sg = ec2.create_security_group(GroupName='webServer', Description = 'WebServer'$
response = sg.authorize_ingress(
IpPermissions=[
{
"FromPort": 22,
"ToPort": 22,
"IpProtocol": "tcp",
"IpRanges": [
{"CidrIp": "0.0.0.0/0", "Description": "WebServer"},
],
},
{
"FromPort": 80,
"ToPort": 80,
"IpProtocol": "tcp",
"IpRanges": [
{"CidrIp": "0.0.0.0/0", "Description": "WebServer"},
],
},
],
)
instance = ec2.create_instances(
ImageId='ami-64ecf1b725342da',
MinCount=1,
MaxCount=1,
InstanceType='t2.nano',
KeyName = 'key2.pem',
UserData = user_data,
SecurityGroupIds=[sg.group_id]
)
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 upload_to_s3(filename, bucket, key):
try:
response = s3.Object(bucket, key).put(Body=open(filename, 'lr'))
print (response)
return response
except Exception as error:
print (error)
file = 'image1.jpg'
bkt = 'ec2-bucket1'
key = 'image1.jpg'
rsp = upload_to_s3(file, bkt, key)
object_acl = s3.ObjectAcl('bucket2','image1.jpg')
response = object_acl.put(
ACL='public-read',
AccessControlPolicy={
'Grants': [
{
'Grantee': {
'BucketName': 'bucket2',
'Key' : 'image1.jpg'
},
'Permission': 'READ'
},
],
}
GrantRead='string',
GrantReadACP='string',
VersionId='string',
)
最干净的方法是将 ACL 指定为上传的一部分:
s3_resource.Bucket(bucket_name).upload_file(filename, key, ExtraArgs={'ACL': 'public-read'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.