'PermissionError: [WinError 32] The process cannot access the file because it is being used by another process (Python/Django)

I know this question has been asked quite a bit on here, however after trying a number of solutions I am unable to figure out how to fix this issue.

I am downloading images from the Google Maps API to generate maps with and without markers. I am using django-cleanup to remove files when deleted from database however the old versions wont delete. Weirdly, django-cleanup works correctly and deletes the associated image when deleting from the Django Admin page but not when deleting the file directly i.e. in file explorer and says it is open in Python. It also deletes correctly when my local server is terminated as you would expect.

Traceback is as follows:

Traceback (most recent call last):
  File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django_cleanup\handlers.py", line 97, in run_on_commit
    file_.delete(save=False)
  File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\db\models\fields\files.py", line 373, in delete
    super().delete(save)
  File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\db\models\fields\files.py", line 105, in delete
    self.storage.delete(self.name)
  File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\core\files\storage.py", line 304, in delete
    os.remove(name)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\Ricki.Demmery\\Desktop\\dev\\acl_acousticapp\\src\\acl_ac
ousticapp\\media\\projects\\9335\\gmaps_markers_5xDqMnc.png'

The call in views.py is as follows:

gmaps = GoogleMapsAPI()
gmaps.location_img(prjID)

My Google Maps class

def create_styled_marker(style_options={},mkr_lat=0,mkr_lng=0):
    opts = ["%s:%s" % (k, v) for k, v in style_options.items()]
    return '|'.join(opts) + '|{mkr_lat},{mkr_lng}|'.format(mkr_lat=mkr_lat,
                                                            mkr_lng=mkr_lng)

class GoogleMapsAPI:
    def __init__(self):
        self.api_key = settings.GOOGLE_API_KEY

    def location_img(self, proj_id):
        url = "https://maps.googleapis.com/maps/api/staticmap?"

        proj = Project.objects.get(project_ID = proj_id)
        site_lng = proj.site_lon
        site_lat = proj.site_lat
        site_zoom = proj.site_zoom
        monitoring_zoom = proj.monitoring_zoom
        site_loc = str(site_lat) + ',' + str(site_lng)
        scale = 1
        img_size = 800
        markers = []
        mkr_size = 'large'
        mkr_color = 'blue'

        mon_sheets = MonitoringSheet.objects.filter(project_id=proj)
        for m in mon_sheets:
            mkr_lbl = m.monsheet_id
            params = {
            'size':mkr_size,
            'color':mkr_color,
            'label':mkr_lbl,
            }
            marker_str = create_styled_marker(params,m.lat,m.lng)
            markers.append(marker_str)

        urlparams = {'center':str(site_loc),
                    'zoom':str(site_zoom),
                    'size':'%dx%d' % (img_size, img_size),
                    'maptype':'satellite',
                    'sensor':'false',
                    }

        urlparams_markers = {'center':str(site_loc),
                            'zoom':str(monitoring_zoom),
                            'size':'%dx%d' % (img_size, img_size),
                            'maptype':'satellite',
                            'markers':markers,
                            'sensor':'false',
                            }

        if self.api_key is not None:
            urlparams['key'] = self.api_key
            urlparams_markers['key'] = self.api_key

        try:
            response = requests.get(url, params=urlparams)
            response.raise_for_status()
            response2 = requests.get(url, params=urlparams_markers)
            response2.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(e)
            sys.exit(1)

        temp_file = "gmaps.png"
        temp_file_markers = "gmaps_markers.png"
        with open(temp_file,"wb") as f:
            f.write(response.content)
        with open(temp_file_markers,"wb") as f:
            f.write(response2.content)

        proj_obj = Project.objects.get(project_ID=proj_id)
        report_obj = ReportDetail.objects.get(project_ID=proj_obj)

        with open(temp_file,"rb") as reopen:
            django_file = File(reopen)
            report_obj.site_location.save(temp_file,
                                        django_file,
                                         save=False)
        with open(temp_file_markers,"rb") as reopen2:
            django_file2 = File(reopen2)
            report_obj.monitoring_locations.save(temp_file_markers,
                                                      django_file2,
                                                        save=False)

        # resp = {'filename':temp_file,
        #         'file':django_file,
        #         'filename2':temp_file_markers,
        #         'file2':django_file2,
        #         }

        report_obj.save()
        return None


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source