'Is it able to delete the file after I send files in Django

from django.http import FileResponse
def send_file():
    #some processes
    response = FileResponse(open(file_name, 'rb'),as_attachment=True)
    return response

I want to delete the file after my web app send it, but my server on Heroku only have 512M . So I can't use too much memory. How can I do that? Many thanks



Solution 1:[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.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Gavriel Cohen