如何使用 python boto3 代码在 s3 存储桶中创建文件夹

问题描述 投票:0回答:2

在S3存储桶中,folder_name由company_id保存。我正在根据 s3 存储桶中的company_id传递company_id,必须检查company_id是否存在。

  • 如果company_id不在S3存储桶中,则必须创建一个新文件夹并上传文件
  • 否则 company_id 位于 s3 存储桶中,则文件应插入到该文件夹中。

但我不知道如何检查这个条件,我有一个上传文件代码,但必须检查这个条件。这是我的代码:

class AddImageUpload(APIView):
    def post(self, request):
        try:
            myfile = request.FILES['fileUpload']
            myfolder = request.Folders['company_id']
            user_id=request.data.get("ip_user_id")
            company_id = request.data.get("ip_company_id")
            now = datetime.datetime.now()
            timestamp =  int(datetime.datetime.timestamp(now))
            print("timestamp =", timestamp)
            fsize = myfile.files[0].size;
            # // Size
            # returned in bytes.
            fsizekb = fsize / 1024;
            # Convert to KBytes
            # #
            # if (fsizekb > 100):
            #    {
            #      alert('Your File size is more than specific size; Size of your file'+fsizekb.toFixed(2)+'KB')
            #       return HttpResponse ('false')
            #    }
            #     {
            #       var
            #        objFSO = new
            #        ActiveXObject("Scripting.FileSystemObject");
            #      var
            #         e = objFSO.getFile(fileInput.value);
            #     var
            #     fileSize = e.size;
            #     var
            #     fsizekb = filesize / 1024;
            #
            #     if (fsizekb > 100){
            #     alert("Your File size is more than specific size; Size of your file.(CC)"+fsizekb.toFixed(2)+" KB");
            #     return false;
            #     }
            #     }
            #     return true;

            res = upload_to_aws(myfile,user_id,myfile.name,timestamp,company_id,myfolder)
            if res == True:
                result = settings.S3BucketLink + myfile.name
                returnobj = {
                    'isuploaded': res,
                    'imageurl': result
                }
                return HttpResponse(json.dumps(returnobj))
            else:
                returnobj = {
                    'isuploaded': res,
                    'imageurl': ""
                }
                return HttpResponse(json.dumps(returnobj))
        except Exception as err:
            http_err = traceback.format_exc()
            self.error_logger.error(http_err)
            return HttpResponse(err)
        finally:
            execute_function().close_db_connection()


def upload_to_aws(filedata,user_id,filename,timestamp,company_id,myfolder):
    s3 = boto3.client('s3', aws_access_key_id=settings.S3_BUCKET_BUCKET_AccessKeyId,
                      aws_secret_access_key=settings.S3_BUCKET_BUCKET_SecretAccessKey)

    try:
        curntfilename = filedata.name+str(timestamp)
        data = s3.upload_fileobj(filedata, settings.S3_BUCKET_BUCKET_NAME, '%s/%s' % (settings.users, filename))
        uploadprofile(user_id,curntfilename,company_id,myfolder)
        print("Upload Successful")
        return True
    except FileNotFoundError:
        print("The file was not found")
        return False
    except NoCredentialsError:
        print("Credentials not available")
        return False

def uploadprofile(user_id,curntfilename,company_id):
            try:
                company_id = company_id
                execute_function.get_connection_by_company(company_id)
                params = {
                    'ip_profile_name': curntfilename,
                    'ip_user_id':user_id
                }
                result = execute_function.put(params, db_functions.fn_ins_upd_user_profile)
                return HttpResponse(result)
            except Exception as err:
                http_err = traceback.format_exc()
                print(http_err)
                return HttpResponse(http_err, status=500)
            finally:
                execute_function().close_db_connection()
python python-3.x amazon-web-services amazon-s3 boto3
2个回答
4
投票

Amazon S3 实际上并不使用文件夹。相反,对象的

Key
(文件名)包含对象的 完整路径

这意味着 您可以将文件上传到文件夹,即使该文件夹不存在! 该文件夹将自动“显示”在 Amazon S3 中。稍后,如果您删除“文件夹”中的所有文件,则该文件夹将消失(因为它实际上从未存在过)。

虽然您可以通过 Amazon S3 管理控制台创建“文件夹”,但这实际上会创建一个与文件夹同名的零长度对象。这会强制文件夹出现在用户界面中,但实际上并不会创建“文件夹”(因为文件夹不存在)。

底线: 只需假装您想要的文件夹存在并随意上传即可。然后它就会“出现”。无需在 Amazon S3 存储桶中创建文件夹。


1
投票

S3 是一个基于密钥的对象存储,文件夹实际上只是为了方便添加密钥前缀。

为了知道“文件夹”是否存在,您真正要问的是存储桶中是否有任何以“文件夹”为前缀的键

import boto3

resp = boto3.client('s3').list_objects_v2(
  Bucket=bucket,
  Prefix=prefix,
  MaxKeys=1
)

if resp['Contents']:
  return f'prefix {prefix} exists'

如果前缀存在,

resp['Contents']
的评估将返回True

请参阅 https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.list_objects_v2 了解有关响应和请求选项的更多信息

© www.soinside.com 2019 - 2024. All rights reserved.