Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Python

AWS Resource का उपयोग करके Boto3 लाइब्रेरी से S3 में ऑब्जेक्ट कैसे अपलोड करें?


समस्या विवरण

Python में Boto3 लाइब्रेरी का उपयोग करके S3 में ऑब्जेक्ट अपलोड करें। उदाहरण के लिए, test.zip को S3 के Bucket_1 में कैसे अपलोड करें।

इस समस्या को हल करने का दृष्टिकोण/एल्गोरिदम

चरण 1 - अपवादों को संभालने के लिए boto3 और botocore अपवाद आयात करें।

चरण 2 - pathlib से PurePosixPath आयात करें ताकि पथ से फ़ाइलनाम प्राप्त किया जा सके।

चरण 3 - s3_path और filepath फ़ंक्शन upload_object_into_s3 में दो पैरामीटर हैं।

चरण 4 - मान्य करें कि s3_path AWS प्रारूप में s3://bucket_name/key के रूप में पारित किया गया है और filepath स्थानीय पथ C://users/filename के रूप में है।

चरण 5 - boto3 लाइब्रेरी का उपयोग करके AWS सत्र बनाएं।

चरण 6 - S3 के लिए AWS रिसोर्स बनाएं।

चरण 7 - S3 पथ को विभाजित करें और रूट बकेट नाम और कुंजी पथ को अलग करने के लिए संचालन करें।

चरण 8 - पूर्ण फ़ाइलपथ से फ़ाइल नाम प्राप्त करें और S3 कुंजी पथ में जोड़ें।

चरण 9 - अब स्थानीय फ़ाइल को S3 में अपलोड करने के लिए upload_fileobj फ़ंक्शन का उपयोग करें।

चरण 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:
        # स्थानीय पथ से एंटिटी अपलोड कर रहे हैं
        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

  1. - Python का उपयोग करके कैसे जांचें कि कोई फाइल मौजूद है या नहीं?

    कंप्यूटर में किसी विशेष फाइल की उपस्थिति को Python कोड का उपयोग करके दो तरीकों से सत्यापित किया जा सकता है। एक तरीका os.path मॉड्यूल के isfile() फंक्शन का उपयोग करना है। यदि निर्दिष्ट पथ पर फाइल मौजूद है तो फंक्शन True लौटाता है, अन्यथा False लौटाता है। >>> import os >>> os.path.is

  1. - Python का उपयोग करके File Extension कैसे Extract करें?

    File Extension Extract करना आप os.path.splitext Method का उपयोग करके Filename String से File Extension Extract कर सकते हैं। यह Pathname Path को एक Pair (root, ext) में Split करता है जैसे कि root + ext == path, और ext Empty होता है या Period से शुरू होता है और अधिकतम एक Period रखता है। उदाहरण impor

  1. - पायथन का उपयोग करके एकाधिक फ़ाइलों को रिकर्सिवली कैसे रीनेम करें?

    आप डायरेक्टरी के माध्यम से रिकर्सिवली चलने के लिए os.walk का उपयोग कर सकते हैं और बाद में फ़ाइलों को रीनेम करने के लिए os.rename का उपयोग कर सकते हैं। उदाहरण import os def replace(folder_path, old, new): for path, subdirs, files in os.walk(folder_path): for name in files: if