Example #1
0
def remove_profile_image(user):
    S3_BUCKET = settings.S3_BUCKET
    AWS_ACCESS_KEY_ID = settings.AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY = settings.AWS_SECRET_ACCESS_KEY
    conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
    url_list1 = user.profile_image_url.split("/")
    filename1 = url_list1[len(url_list1) - 1]
    url_list2 = user.profile_image_crop.url.split("/")
    filename2 = url_list2[len(url_list2) - 1]

    b = Bucket(conn, S3_BUCKET)

    k = Key(b)

    k.key = 'profile_images/' + filename1

    b.delete_key(k)

    k.key = 'profile_images/crop/' + filename2

    b.delete_key(k)

    user.profile_image_url = None
    user.profile_image_crop = None
    user.save()
Example #2
0
def delete_from_S3(filename):
    conn = S3Connection(settings.AWS_ACCESS_KEY_ID,
                        settings.AWS_SECRET_ACCESS_KEY)
    bucket = Bucket(conn, settings.AWS_STORAGE_BUCKET_NAME)
    k = Key(bucket)
    k.key = settings.MEDIA_URL + filename
    bucket.delete_key(k)
def delete_from_s3(image_name):
    """Delete image from S3 bucket"""
    conn = S3Connection(aws_access_key_id, aws_secret_access_key)
    bucket = Bucket(conn, "shopifyimagerepository")
    k = Key(bucket)
    k.key = image_name
    bucket.delete_key(k)
def deletePreviousS3Files(bucketName, data_path):
    print("Deleting S3 otodompl Deals Files")

    conn = S3Connection()
    b = Bucket(conn, bucketName)
    for x in b.list(prefix=data_path + 'deals/otodompl/'):
        x.delete()
Example #5
0
    def handle(self, *args, **options):
        print('Loading list of S3 files')

        conn = S3Connection(settings.AWS_ACCESS_KEY_ID,
                            settings.AWS_SECRET_ACCESS_KEY)
        bucket = Bucket(conn, settings.AWS_STORAGE_BUCKET_NAME)

        s3_files = set()
        for key in bucket.list():
            s3_files.add(key.name)

        print('Loaded {} S3 files'.format(len(s3_files)))

        startdate = timezone.now() - timedelta(
            days=int(options["no_of_days_back"]))
        attachments = Attachment.objects.select_related('report')\
            .filter(report__created_at__gte=startdate)
        for attachment in attachments:
            if attachment.attachment not in s3_files:
                attachment.delete()
                sys.stdout.write('-')
            else:
                sys.stdout.write('+')
            sys.stdout.flush()

        print('Deleting empty reports')
        with connection.cursor() as cursor:
            cursor.execute(
                "delete from report_report WHERE "
                "(description is NULL or description = '') AND "
                "(select count(*) from report_attachment where report_id=report_report.id) =0"
            )
Example #6
0
def test_upload_and_download_with_encryption(tmpdir):
    from toil_lib.urls import s3am_upload
    from toil_lib.urls import download_url
    from boto.s3.connection import S3Connection, Bucket, Key
    work_dir = str(tmpdir)
    # Create temporary encryption key
    key_path = os.path.join(work_dir, 'foo.key')
    subprocess.check_call([
        'dd', 'if=/dev/urandom', 'bs=1', 'count=32', 'of={}'.format(key_path)
    ])
    # Create test file
    upload_fpath = os.path.join(work_dir, 'upload_file')
    with open(upload_fpath, 'wb') as fout:
        fout.write(os.urandom(1024))
    # Upload file
    random_key = os.path.join('test/', str(uuid4()), 'upload_file')
    s3_url = os.path.join('s3://cgl-driver-projects/', random_key)
    try:
        s3_dir = os.path.split(s3_url)[0]
        s3am_upload(fpath=upload_fpath, s3_dir=s3_dir, s3_key_path=key_path)
        # Download the file
        download_url(url=s3_url,
                     name='download_file',
                     work_dir=work_dir,
                     s3_key_path=key_path)
        download_fpath = os.path.join(work_dir, 'download_file')
        assert os.path.exists(download_fpath)
        assert filecmp.cmp(upload_fpath, download_fpath)
    finally:
        # Delete the Key. Key deletion never fails so we don't need to catch any exceptions
        with closing(S3Connection()) as conn:
            b = Bucket(conn, 'cgl-driver-projects')
            k = Key(b)
            k.key = random_key
            k.delete()
Example #7
0
def deletePreviousS3Files(bucketName, data_path):
	print("Deleting S3 Stvpt Contacts Files")

	conn = S3Connection()
	b = Bucket(conn, bucketName)
	for x in b.list(prefix = data_path + 'contacts/stvpt/'):
		x.delete()
Example #8
0
def delete_product_image(product):
    S3_BUCKET = settings.S3_BUCKET
    AWS_ACCESS_KEY_ID = settings.AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY = settings.AWS_SECRET_ACCESS_KEY
    conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
    url_list1 = product.image_url.split("/")
    filename1 = url_list1[len(url_list1) - 1]
    url_list2 = product.thumbnail.url.split("/")
    filename2 = url_list2[len(url_list2) - 1]
    url_list3 = product.watermark.url.split("/")
    filename3 = url_list3[len(url_list3) - 1]

    b = Bucket(conn, S3_BUCKET)

    k = Key(b)

    k.key = 'products/' + filename1

    b.delete_key(k)

    k.key = 'products/thumbnails/' + filename2

    b.delete_key(k)

    k.key = 'products/watermarked/' + filename3

    b.delete_key(k)
def deletePreviousS3Files(conf_file, keyId, sKeyId):
    print("Deleting S3 Stvpt Contacts Files")
    conf = json.load(open(conf_file))

    conn = S3Connection(keyId, sKeyId)
    b = Bucket(conn, 'pyrates-eu-data-ocean')
    for x in b.list(prefix='crm-automations/contacts/stvpt/'):
        x.delete()
Example #10
0
 def tearDown(self):
     shutil.rmtree(self.workdir)
     with closing(S3Connection()) as s3:
         bucket = Bucket(s3, self.output_dir.netloc)
         prefix = self.output_dir.path[1:]
         for key in bucket.list(prefix=prefix):
             assert key.name.startswith(prefix)
             key.delete()
def deletePreviousS3Files(conf_file):
	conf = json.load(open(conf_file))
	bucket_name = conf['bucket_name']

	conn = S3Connection()
	b = Bucket(conn, bucket_name)
	for x in b.list(prefix = 'Aux/'):
		x.delete()
Example #12
0
def deletePreviousS3Files(conf_file, keyId, sKeyId):
	print("Deleting S3 Atvro Deals Files")
	conf = json.load(open(conf_file))

	conn = S3Connection(keyId, sKeyId)
	b = Bucket(conn, 'pyrates-data-ocean')
	for x in b.list(prefix = 'renato-teixeira/deals/atvro/'):
		x.delete()
Example #13
0
def deletePreviousS3Files(conf_file):
    conf = json.load(open(conf_file))
    key = conf['s3_key']
    skey = conf['s3_skey']

    conn = S3Connection(key, skey)
    b = Bucket(conn, 'verticals-raw-data')
    for x in b.list(prefix='vas/silver'):
        x.delete()
Example #14
0
def delete_img_aws(instance, **kwargs):
    conn = S3Connection(settings.AWS_ACCESS_KEY_ID,
                        settings.AWS_SECRET_ACCESS_KEY)
    b = Bucket(conn, settings.AWS_STORAGE_BUCKET_NAME)
    img_k = Key(b)
    img_thumb_k = Key(b)
    img_k.key = instance.image.name
    img_thumb_k.key = instance.image_thumb.name
    b.delete_key(img_k)
    b.delete_key(img_thumb_k)
Example #15
0
def delete_image_from_s3(file_name):
    try:
        conn = S3Connection(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        logging.info("success s3 connection")
        bucket = Bucket(conn, BUCKET)
        k = Key(bucket=bucket, name=file_name)
        k.delete()
        logging.info("success delete image from s3")
    except Exception as e:
        logging.debug(e)
Example #16
0
 def cleanupBucket(self, bucket_name):
     try:
         from boto.s3.connection import S3Connection, Bucket, Key
         conn = S3Connection()
         b = Bucket(conn, bucket_name)
         for x in b.list():
             b.delete_key(x.key)
         b.delete()
     except:
         pass  # bucket must already be removed
Example #17
0
 def _assertOutput(self, num_samples=None, bam=False):
     with closing(S3Connection()) as s3:
         bucket = Bucket(s3, self.output_dir.netloc)
         prefix = self.output_dir.path[1:]
         for i in range(1 if num_samples is None else num_samples):
             value = None if num_samples is None else i
             output_file = self._sample_name(value, bam=bam) + '.tar.gz'
             key = bucket.get_key(posixpath.join(prefix, output_file),
                                  validate=True)
             # FIXME: We may want to validate the output a bit more
             self.assertTrue(key.size > 0)
Example #18
0
def s3_delete_image(data):

    try:
        from boto.s3.connection import S3Connection, Bucket, Key
        conn = S3Connection(data['S3_KEY'], data['S3_SECRET'])
        b = Bucket(conn, data['S3_BUCKET'])
        k = Key(b)
        k.key = data['S3_UPLOAD_DIRECTORY'] + '/' + data['destinationFileName']
        b.delete_key(k)

    except Exception as e:
        return e
Example #19
0
def deletePreviousS3Files(conf_file, bucket_name, s3_path_prefix, scai_last_execution_status=1):

	if (scai_last_execution_status!=3):
		conf = json.load(open(conf_file))
		key = conf['s3_key']
		skey = conf['s3_skey']

		conn = S3Connection(key, skey)

		b = Bucket(conn, bucket_name)
		for x in b.list(prefix = s3_path_prefix):
			x.delete()
Example #20
0
def delete_file_from_s3(filename):
    conn = S3Connection(
        settings.AWS_ACCESS_KEY_ID,
        settings.AWS_SECRET_ACCESS_KEY,
    )
    b = Bucket(
        conn,
        settings.AWS_STORAGE_BUCKET_NAME,
    )
    k = Key(b)
    k.key = filename
    b.delete_key(k)
Example #21
0
    def perform_destroy(self, instance):
        conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, host='s3.ap-northeast-2.amazonaws.com')
        b = Bucket(conn, settings.AWS_STORAGE_BUCKET_NAME)
        k = Key(b)

        k.key = str(instance.left_footscan_stl)
        b.delete_key(k)

        k.key = str(instance.right_footscan_stl)
        b.delete_key(k)

        instance.delete()
def checkS3FileExists(bucket, path):
    conn = S3Connection()
    b = Bucket(conn, bucket)
    found_file = 'false'

    for x in b.list(prefix=path[1:]):
        if (len(str(x)) > 0):
            print(path)
            found_file = 'true'
            break

    return found_file
Example #23
0
 def _assertOutput(self, num_samples=None):
     with closing(S3Connection()) as s3:
         bucket = Bucket(s3, self.output_dir.netloc)
         prefix = self.output_dir.path[1:]
         for i in range(1 if num_samples is None else num_samples):
             output_file = self._sample_name(
                 None if num_samples is None else i) + '.tar.gz'
             output_file = 'FAIL.' + output_file  # This flag is added by bamQC
             key = bucket.get_key(posixpath.join(prefix, output_file),
                                  validate=True)
             # FIXME: We may want to validate the output a bit more
             self.assertTrue(key.size > 0)
Example #24
0
def prop(request, prop_id):
    if request.method == "GET":
        domain = request.get_host()
        # GET - READ
        try:
            prop = Prop.objects.get(id=prop_id)
            response_data = {
                "success": True,
                "prop": {
                    "id": prop.id,
                    "name": prop.name,
                    "description": prop.description,
                    "url": prop.image.url
                }
            }
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json")
        except ObjectDoesNotExist:
            return HttpResponse(status=404)
    elif request.method == "PUT":
        # PUT - UPDATE - later
        pass
    elif request.method == "DELETE":
        prop = Prop.objects.get(id=prop_id)
        # Unset From all scenes and delete scene_prop
        scene_props = SceneProp.objects.filter(prop_file=prop)
        for scene_prop in scene_props:
            scene = scene_prop.scene
            scene_prop.delete()
            scene.save()
        # Delete File
        if prop.image:
            if not settings.USE_AWS and prop.image.path:
                # Delete from MEDIA_ROOT
                os.remove(prop.image.path)
            elif settings.USE_AWS and prop.image.name:
                # Delete from AWS S3
                connection = S3Connection(settings.AWS_ACCESS_KEY_ID,
                                          settings.AWS_SECRET_ACCESS_KEY)
                bucket = Bucket(connection, settings.AWS_STORAGE_BUCKET_NAME)
                fileKey = Key(bucket)
                fileKey.key = prop.image.name
                bucket.delete_key(fileKey)
        # Delete From Database
        prop.delete()
        response_data = {"success": True}
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")
    else:
        return HttpResponseNotAllowed(['GET', 'PUT', 'DELETE'])
    return HttpResponse("API call for prop #" + prop_id)
Example #25
0
def upload():
    s3_conn = s3()

    #     bucket = s3_conn.create_bucket('distributed-web-crawler')
    bucket = Bucket(s3_conn, 'distributed-web-crawler')

    k = Key(bucket)

    k.key = 'list_links_a.txt'
    k.set_contents_from_filename('input_links_a.txt')

    os.remove('input_links_a.txt')

    s3_conn.close()
def delete():
    file_name1=request.form.get("del_filename")
    print "Filename is "
    print file_name1

    conn = S3Connection(cfg.AWS_APP_ID, cfg.AWS_APP_SECRET)
    bucket = Bucket(conn, cfg.AWS_BUCKET)
    key = 'uploads/' + secure_filename(file_name1)
    k = Key(bucket=bucket, name=key)
    k.delete()
    flash("File Delete successfully")
    return render_template('index.html')

    return file_name1
def checkS3FileExists(conf_file, bucket, path):
    conf = json.load(open(conf_file))
    key = conf['s3_key']
    skey = conf['s3_skey']
    conn = S3Connection(key, skey)
    b = Bucket(conn, bucket)
    found_file = 'false'

    for x in b.list(prefix=path[1:]):
        if (len(str(x)) > 0):
            print(path)
            found_file = 'true'
            break

    return found_file
Example #28
0
    def run(self):
        s3 = boto3Conn()
        s3content = s3.list_objects_v2(Bucket='rmsapi')['Contents']
        s3files = [s['Key'] for s in s3content]
        s3 = s3open()
        s3read = s3.Bucket('rmsapi')

        if len(s3files) > 59:
            # Creates data frames and assigns columns
            E_cols = ['id', 'etype', 'diff', 'lon', 'lat', 'bear', 'road', 'dat']
            I_cols = ['id', 'lon', 'lat', 'itype', 'street', 'dat_str', 'dat_end', 'ended']
            df_outE = pd.DataFrame(columns=E_cols)
            df_outI = pd.DataFrame(columns=I_cols)
            timelist = []

            # Iterates over files and stores the timestamp of the file
            for file in s3read.objects.all():
                key = file.key
                body = file.get()['Body'].read()
                timestamp = re.findall('[^_]+', key)
                timestamp = timestamp[1].replace('+', ':')
                timelist.append(timestamp)

                # Different methods for event and incident files
                if key.startswith('event'):
                    df_outE = parseEvent(body, timestamp, df_outE)
                if key.startswith('inciden'):
                    df_outI = parseIncident(body, timestamp, df_outI)

            # Output to csv file
            with self.output()[0].open('w') as csvfile:
                df_outE['diff'] = df_outE['diff'].astype(int)
                df_outE['id'] = pd.to_numeric(df_outE['id'])
                df_outE.to_csv(csvfile, columns=E_cols, index=False)

            with self.output()[1].open('w') as csvfile:
                # Create an end time stamp for data that has not actually ended yet for Gantt file
                df_outI = endIncidents(timelist, df_outI)
                df_outI['id'] = df_outI['id'].astype(int)
                df_outI.to_csv(csvfile, columns=I_cols, index=False)

            s3del = Bucket(s3delete(),'rmsapi')
            k = Key(s3del)

            # Delete all files in S3 folder
            for file in s3files:
                k.key = file
                s3del.delete_key(k)
Example #29
0
    def post(self, request, business_id):
        business = get_object_or_404(Business, pk=business_id)

        if business.image and business.image.url:
            conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
            bucket = Bucket(conn, settings.AWS_STORAGE_BUCKET_NAME)
            k = Key(bucket=bucket, name=business.image.url.split(bucket.name)[1])
            k.delete()

        file = request.FILES.get('file')
        business.image = file
        business.save()

        request.session['business_image'] = business.image.url if business.image and business.image.url else None

        return Response({}, status=status.HTTP_200_OK)
Example #30
0
def background(request, background_id):
    domain = request.get_host()
    if request.method == "GET":
        # GET - READ
        try:
            background = Background.objects.get(id=background_id)
            response_data = {
                "success": True,
                "background": {
                    "id": background.id,
                    "name": background.name,
                    "description": background.description,
                    "url": background.image.url
                }
            }
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json")
        except ObjectDoesNotExist:
            return HttpResponse(status=404)
    elif request.method == "PUT":
        # PUT - UPDATE - later
        pass
    elif request.method == "DELETE":
        background = Background.objects.get(id=background_id)
        # Unset From all scenes
        background.scenes.clear()
        # Delete File
        if background.image:
            if not settings.USE_AWS and background.image.path:
                # Delete from MEDIA_ROOT
                os.remove(background.image.path)
            elif settings.USE_AWS and background.image.name:
                # Delete from AWS S3
                connection = S3Connection(settings.AWS_ACCESS_KEY_ID,
                                          settings.AWS_SECRET_ACCESS_KEY)
                bucket = Bucket(connection, settings.AWS_STORAGE_BUCKET_NAME)
                fileKey = Key(bucket)
                fileKey.key = background.image.name
                bucket.delete_key(fileKey)
        # Delete from database
        background.delete()
        response_data = {"success": True}
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")
    else:
        return HttpResponseNotAllowed(['GET', 'PUT', 'DELETE'])
    return HttpResponse("API call for background #" + background_id)