Home > Mobile >  How to handle file delete after returning it has response in Django rest framework
How to handle file delete after returning it has response in Django rest framework

Time:12-29

I am performing the below steps in my DRF code.

  1. Capturing the file name in a request
  2. Searching the given file name in a SFTP server.
  3. If the file is available in SFTP server,downloading it to local path in a folder called "downloads"
  4. Returning the file as response with FileResponse

I need to delete the file which i downloaded from SFTP or simply delete everything in downloads folder.

What is the best approach to achieve this? How about an async celery task before returning FileResponse?

CodePudding user response:

One way to solve this problem is to use the Python module tempfile, which provides temporary files which are automatically deleted when all references in Python are removed.

Here's an example from the documentation:

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

Once you have this file object, you can use FileResponse to send it back to the client.

An alternate way would be to use a cronjob to delete files older than a certain number of days.

  • Related