[docs]defvalidate_s3_bucket(bucket:str)->None:""" Raise exception if validation not passed. Ref: - `Bucket naming rules <https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html>`_ """ifnot(3<=len(bucket)<=63):raiseValueError("Bucket names must be between 3 and 63 characters long.")invalid_chars=set(bucket).difference(valid_bucket_charset)iflen(invalid_chars)!=0:raiseValueError(("Bucket names can consist only of lowercase letters, numbers, ""dots (.), and hyphens (-). invalid char found {}").format(invalid_chars))if(bucket[0]notinletter_and_number)or(bucket[-1]notinletter_and_number):raiseValueError("Bucket names must begin and end with a letter or number.")try:parts=[int(part)forpartinbucket.split(".")]assertlen(parts)==4forpinparts:assert0<=p<=255raiseS3BucketValidationError("Bucket names must not be formatted as an IP address (for example, 192.168.5.4).")exceptS3BucketValidationErrorase:raiseeexcept:passifbucket.startswith("xn--"):raiseValueError("Bucket names must not start with the prefix xn--.")ifbucket.endswith("-s3alias"):raiseValueError("Bucket names must not end with the suffix -s3alias. This suffix is reserved for access point alias names.")
# raise ValueError("Buckets used with Amazon S3 Transfer Acceleration can't have dots (.) in their names.")
[docs]defvalidate_s3_key(key:str)->None:""" Raise exception if validation not passed. Ref: - `Key naming rules <https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html#object-key-guidelines>`_ """iflen(key)>1024:raiseValueError("S3 key must be less that 1024 chars ""to construct the S3 console url!")invalid_chars=set(key).difference(valid_key_charset)iflen(invalid_chars)!=0:doc_url="https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html#object-key-guidelines"raiseValueError(("Invalid char found {}, ""read {} ""for more info").format(invalid_chars,doc_url))
[docs]defvalidate_s3_uri(uri:str)->None:""" Raise exception if validation not passed. S3 URI is just ``s3://{bucket}/{key}`` """ifnoturi.startswith("s3://"):raiseValueError("S3 URI must starts with 's3://'")ifuri.count("/")<3:raiseValueError("S3 URI must have at least three '/', ""for example: s3://bucket/")parts=uri.split("/",3)bucket=parts[2]key=parts[3]validate_s3_bucket(bucket)validate_s3_key(key)
[docs]defvalidate_s3_arn(arn:str)->None:""" Raise exception if validation not passed. S3 ARN is just: - for bucket: ``arn:aws:s3:::{bucket}`` - for object: ``arn:aws:s3:::{bucket}/{key}`` - for directory: ``arn:aws:s3:::{bucket}/{prefix}/`` """ifnotarn.startswith("arn:aws:s3:::"):raiseValueError("S3 ARN must starts with 'arn:aws:s3:::'")path=arn.replace("arn:aws:s3:::","",1)if"/"notinpath:# path is the bucketvalidate_s3_bucket(path)else:bucket,key=path.split("/",1)validate_s3_bucket(bucket)validate_s3_key(key)