Python – How to remove a temporary file (image) that is being displayed by CGI


I've written a python CGI script that converts files into .jpgs and displays them in a simple HTML page. I don't want to clutter up the folders with these .jpg files, so I used tempfile.NamedTemporaryFile to create a file to store the converted .jpg output. Everything works great, but i want to remove this file after the page is displayed. Currently I have delete=False set, but i can't seem to remove the file without causing a broken img link.

Best Solution

You can't remove the file from your cgi script. Because the html page is send to the user only after your script finishes to run. And then the users browser parse the html and fetch the jpg file.

The simplest option is to write the temporary files to a sub directory and periodically clean that directory (living in it the last few minutes only). There are ways to improve this process but they are probably pointless.

A more advanced option (which is also probably pointless, depending on your scenario) is to configure the web server to run a script on the "get jpg" request. And then you can stream the jpg through your script. That way you will know when the jpg was fetched. And in this script you can call a subscript asynchronically to delete the jpg file.