1👍
The simplest solution is to use TemporaryFile which will be deleted on close (in your case FileResponse will close the file).
If this solution is not applicable for your case (because of the file is already exists in your example), you can use the approach similar to django.db.transaction.on_commit (I mean similar to how it is implemented in its source code):
- define the queue to store file paths to be deleted;
- implement the queue handler to remove all queued files by their file paths and clean the queue;
- connect the queue handler with
request_finished
signal (Django will send it when finishes delivering an HTTP response to the client); - push current
file_name
to the queue while handling the request.
FileResponse will read the file in chunks of 4kb (default) to transfer it to the client. The file will be deleted using the operating system functionality. Therefore both of these approaches will not consume much more memory.
Also, you can add an additional periodic task to clean up obsolete files, if you need a very robust solution.
👤zok
Source:stackexchange.com