Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Currently 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"

  1. Returning the file as response with FileResponse

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What will be best approach to achieve this?
How about an async celery task before returning FileResponse.

Kindly help me with the best approach for this

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading