Home > Back-end >  Deleting an unused image in s3 Bucket in Flask
Deleting an unused image in s3 Bucket in Flask

Time:01-25

I have a route in my FLASK api which uploads an image to my s3 bucket and then saves the url to a avatar_url field on a user object.

@bp.route('/user/<userid>/files-upload', methods=['POST'])
def upload_file(userid):

  user = db_session.query(User).get(userid)

  img = request.files['file']
  if img:
          filename = secure_filename(img.filename)
          img.save(filename)
          s3.upload_file(
              Bucket = bucket,
              Filename = filename,
              Key = filename,
              ExtraArgs={
                "ACL": 'public-read',
                "ContentType": img.content_type  
              }
            )
          msg = "Upload Done ! "
          
  url = f'https://{bucket}.s3.amazonaws.com/{filename}'

  user.avatar_url = url

  try:
        db_session.commit()
        return user_schema.dumps(user)
  except:
        db_session.rollback()
        raise

This is working nicely but then I realized if the user goes and changes their picture a number of times, this could result in a bunch of unused files sitting around and clogging up my bucket. I would imagine I need to draft up some functionality that deletes the old file(if there is one)? Then save the new file? Any suggestions would be greatly appreciated.

CodePudding user response:

I would recommend to use the ID of the user as the object key in the S3, this will offer the following advantages:

  • Any previous file uploaded by the user gets overridden by a new upload. This automatically removes the need to monitor and seek old files.
  • If the organization decides to start keeping old versions, it will be easy to enable object versioning which allows you guys to keep older versions of profile photos.
avatar-s3/user-1.png
avatar-s3/user-2.png
  •  Tags:  
  • Related