-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload_data_to_s3.py
More file actions
62 lines (56 loc) · 2.26 KB
/
Copy pathupload_data_to_s3.py
File metadata and controls
62 lines (56 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
BUCKET = os.environ.get('S3_BUCKET', 'ml-crash-course-data')
KEY = os.environ.get('S3_KEY', 'House_Rent_Dataset.csv')
LOCAL_PATH = os.environ.get('LOCAL_PATH', 'data/House_Rent_Dataset.csv')
ENDPOINT_URL = os.environ.get('S3_ENDPOINT_URL') # For MinIO/local
session = boto3.session.Session()
s3 = session.client('s3', endpoint_url=ENDPOINT_URL)
def ensure_bucket_exists(bucket):
try:
s3.head_bucket(Bucket=bucket)
print(f"Bucket {bucket} already exists.")
except ClientError as e:
if e.response['Error']['Code'] == '404':
print(f"Bucket {bucket} does not exist. Creating...")
try:
s3.create_bucket(Bucket=bucket)
print(f"Bucket {bucket} created successfully.")
except ClientError as create_error:
print(f"Error creating bucket: {create_error}")
raise
elif e.response['Error']['Code'] == '403':
print(f"Access denied to bucket {bucket}. Trying to upload anyway...")
else:
print(f"Error checking bucket: {e}")
raise
def file_exists(bucket, key):
try:
s3.head_object(Bucket=bucket, Key=key)
return True
except ClientError as e:
if e.response['Error']['Code'] == '404':
return False
elif e.response['Error']['Code'] == '403':
print(f"Access denied checking file existence. Assuming it doesn't exist.")
return False
raise
def upload_file():
try:
if not file_exists(BUCKET, KEY):
print(f'Uploading {LOCAL_PATH} to s3://{BUCKET}/{KEY}')
s3.upload_file(LOCAL_PATH, BUCKET, KEY)
print('Upload complete.')
else:
print(f's3://{BUCKET}/{KEY} already exists. Skipping upload.')
except NoCredentialsError:
print("No AWS credentials found. Please check your credentials.")
except ClientError as e:
print(f"Error during upload: {e}")
if e.response['Error']['Code'] == '403':
print("Access denied. Please check your credentials and permissions.")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == '__main__':
upload_file()