Django celery getting PermissionError when trying to delete file

I am using django celery for downloading and uploading image but when try to delete image after upload more specifically after .save() method got this error

  os.remove(filename)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'UKXCWKYRPMPKNXBK6111_img_91b00679-dc6f-4078-96f6-23c7274d4577_958e8046-4b0f-4396-82c2-0dac374b72df_flaskj.webp'

my image is downloading and uploading but can't delete after upload complete successfully

my celery code:

@shared_task
def download_s3image(image_id,order_id=None):
     s3 = boto3.client('s3')
     image_id =  image_id
     image =  ProductImage.objects.get(id=image_id)
     image = str(image.image)
     img_path = image.replace('product_images/','').replace('.webp','') 
    
     
     # Get the OrderItem model dynamically to avoid circular import
     OrderItem = apps.get_model('order', 'OrderItem')
 
     order_item = OrderItem.objects.get(id=order_id)  # Assuming there is a relationship between OrderItem and Order
     filename = f'{order_item.order.order_id}_img_{img_path}.webp'
     s3.download_file('epeey',image,filename)

     order_item.order_image_file.save(filename, open(filename, 'rb'))
     order_item.save()
     
     #can't remove file using os.remove 
     os.remove(filename)
Back to Top