Issue
I am performing the below steps in my DRF code.
- Capturing the file name in a request
- Searching the given file name in a SFTP server.
- If the file is available in SFTP server,downloading it to local path in a folder called "downloads"
- 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?
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.
Answered By - Nick ODell
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.