Почему Boto3 выдает ошибку создания s3? - PullRequest
0 голосов
/ 14 марта 2020

Почему Boto3 выдает ошибку создания s3? Я пытаюсь создать корзину, но получаю несколько разных ошибок. Я пробовал много способов решить эту проблему, но пока не смог. Благодарю всех за помощь и время.

Ниже вы можете найти код и ситуацию

Мой код ниже:

class BucketManager:  # help us to organized data and code together  
    """"Manage an s3 Bucket."""  
    CHUNK_SIZE = 8388608  
    def __init__(self, session):  # init works as constructor on this line  
        """Crete a BucketManager object."""  
        self.session = session  
        self.s3 = self.session.resource("s3")  
        self.transfer_config = boto3.s3.transfer.TransferConfig(  
            multipart_chunksize=self.CHUNK_SIZE, multipart_threshold=self.CHUNK_SIZE  
        )  
        self.manifest = {}  
    def get_bucket(self, bucket_name):  
        """Get a bucket by name."""  
        return self.s3.Bucket(bucket_name)  
    def get_region_name(self, bucket):  
        """Get the bucket region name"""  
        client = self.s3.meta.client  
        bucket_location = client.get_bucket_location(Bucket=bucket.name)  
        return bucket_location["LocationConstraint"] or "us-east-1"  
    def get_bucket_url(self, bucket):  
        """Get the website URL for this bucket"""  
        return "http://{}.{}".format(  
            bucket.name, util.get_endpoint(self.get_region_name(bucket)).host  
        )  
    def all_buckets(self):  # will return the list of all my s3 bucket  
        """Get an iterator for all buckets."""  
        return self.s3.buckets.all()  
    def all_objects(self, bucket_name):  
        """Get an iterator for all objects in listed buckets."""  
        return self.s3.Bucket(bucket_name).objects.all()  
    def init_bucket(self, bucket_name):  
        """Create new bucket, or return existing one by name."""  
        s3_bucket = None  
        try:  
            s3_bucket = self.s3.create_bucket(  
                Bucket=bucket_name,  
                CreateBucketConfiguration= \  
                    { "LocationConstraint": self.session.region_name  
                },  
            )  
        except ClientError as error:  
            if error.response["Error"]["Code"] == "BucketAlreadyOwnedByYou":  
                s3_bucket = self.s3.Bucket(bucket_name)  
            else:  
                raise error  
                return s3_bucket  
    def set_policy(self, bucket):  
        """Set bucket policy to be readable by everyone"""  
        policy = """  
        {  
          "Version":"2012-10-17",  
          "Statement":[{  
                "Sid":"PublicReadGetObject",  
                "Effect":"Allow",  
                "Principal": "*",  
                "Action":"s3:GetObject",  
                "Resource":"arn:aws:s3:::%s/*"  
            }  
          ]  
        }  
        """ % bucket.name  
        policy = policy.strip()  
        pol = bucket.Policy()  
        pol.put(Policy=policy)  
    def configure_website(self, bucket):  
        bucket.Website().put(  
            WebsiteConfiguration={  
                "ErrorDocument": {"Key": "error.html"},  
                "IndexDocument": {"Suffix": "index.html"},  
            }  
        )

Мой класс

@cli.command('setup-bucket')  
@click.argument('bucket')  
def setup_bucket(bucket):  
    """Create and configure S3 bucket."""  
    s3_bucket = bucket_manager.init_bucket(bucket)  
    bucket_manager.set_policy(s3_bucket)  
    bucket_manager.configure_website(s3_bucket)  
    return

Ошибки

in serialize_to_request  
raise ParamValidationError(report=report.generate_report())  
botocore.exceptions.ParamValidationError: Parameter validation failed:  
Invalid type for parameter CreateBucketConfiguration.LocationConstraint, value: None, type: , valid types:     
File "/Users/name/Desktop/AWS_ALL/automating-aws-with-python/01-webotron/venv/lib/python3.7/site-packages/botocore/validate.py", line 297, in serialize_to_request

raise ParamValidationError(report=report.generate_report())  
botocore.exceptions.ParamValidationError: Parameter validation failed:  
Invalid type for parameter CreateBucketConfiguration.LocationConstraint, value: None, type: , valid types: 

Команды CLI

python3 webotron/webotron_copy.py setup-bucket bigdatalake  
python3 webotron/webotron_copy.py setup-bucket bigdata-lake    
python3 webotron/webotron_copy.py setup-bucket bigdata_lake000000000  

1 Ответ

0 голосов
/ 15 марта 2020

Похоже, что в этом коде self.session.region_name не определено:

            s3_bucket = self.s3.create_bucket(  
                Bucket=bucket_name,  
                CreateBucketConfiguration= \  
                    { "LocationConstraint": self.session.region_name  
                },  
            )  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...