समस्या का विवरण - किसी ऑब्जेक्ट को S3 में अपलोड करने के लिए Python में Boto3 लाइब्रेरी का उपयोग करें। उदाहरण के लिए, test.zip को S3 के बकेट_1 में कैसे अपलोड करें।
इस समस्या को हल करने के लिए दृष्टिकोण/एल्गोरिदम
चरण 1 - अपवादों को संभालने के लिए boto3 और botocore अपवाद आयात करें।
चरण 2 - पाथलिब . से , पथ से फ़ाइल नाम पुनर्प्राप्त करने के लिए PurePosixPath आयात करें
चरण 3 - s3_path और फ़ाइलपथ फ़ंक्शन में दो पैरामीटर हैं upload_object_into_s3
चरण 4 - s3_path की पुष्टि करें एडब्ल्यूएस प्रारूप में s3://bucket_name/key . के रूप में पास किया गया है और फ़ाइलपथ स्थानीय पथ के रूप में C://उपयोगकर्ता/फ़ाइल नाम
चरण 5 - boto3 लाइब्रेरी का उपयोग करके AWS सत्र बनाएं।
चरण 6 - S3 के लिए AWS संसाधन बनाएं।
चरण 7 - S3 पथ को विभाजित करें और रूट बकेट नाम और कुंजी पथ को अलग करने के लिए संचालन करें
चरण 8 - पूर्ण फ़ाइलपथ के लिए फ़ाइल नाम प्राप्त करें और S3 कुंजी पथ में जोड़ें।
चरण 9 - अब फ़ंक्शन का उपयोग करें upload_fileobj स्थानीय फ़ाइल को S3 में अपलोड करने के लिए।
चरण 10 - फ़ंक्शन का उपयोग करें wait_until_exists ऑपरेशन समाप्त होने तक प्रतीक्षा करने के लिए।
चरण 11 - फ़ाइल अपलोड की गई है या नहीं, यह सत्यापित करने के लिए प्रतिक्रिया कोड के आधार पर अपवाद को संभालें।
चरण 12 - फ़ाइल अपलोड करते समय कुछ गलत होने पर सामान्य अपवाद को संभालें
उदाहरण
फ़ाइल को AWS S3 में अपलोड करने के लिए निम्न कोड का उपयोग करें -
import boto3
from botocore.exceptions import ClientError
from pathlib import PurePosixPath
def upload_object_into_s3(s3_path, filepath):
if 's3://' in filepath:
print('SourcePath is not a valid path.' + filepath)
raise Exception('SourcePath is not a valid path.')
elif s3_path.find('s3://') == -1:
print('DestinationPath is not a s3 path.' + s3_path)
raise Exception('DestinationPath is not a valid path.')
session = boto3.session.Session()
s3_resource = session.resource('s3')
tokens = s3_path.split('/')
target_key = ""
if len(tokens) > 3:
for tokn in range(3, len(tokens)):
if tokn == 3:
target_key += tokens[tokn]
else:
target_key += "/" + tokens[tokn]
target_bucket_name = tokens[2]
file_name = PurePosixPath(filepath).name
if target_key != '':
target_key.strip()
key_path = target_key + "/" + file_name
else:
key_path = file_name
print(("key_path: " + key_path, 'target_bucket: ' + target_bucket_name))
try:
# uploading Entity from local path
with open(filepath, "rb") as file:
s3_resource.meta.client.upload_fileobj(file, target_bucket_name, key_path)
try:
s3_resource.Object(target_bucket_name, key_path).wait_until_exists()
file.close()
except ClientError as error:
error_code = int(error.response['Error']['Code'])
if error_code == 412 or error_code == 304:
print("Object didn't Upload Successfully ", target_bucket_name)
raise error
return "Object Uploaded Successfully"
except Exception as error:
print("Error in upload object function of s3 helper: " + error.__str__())
raise error
print(upload_object_into_s3('s3://Bucket_1/testfolder', 'c://test.zip')) आउटपुट
key_path:/testfolder/test.zip, target_bucket: Bucket_1 Object Uploaded Successfully