返回后如何处理文件删除在 Django 休息框架中有响应

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

我正在我的 DRF 代码中执行以下步骤。

  1. 正在抓取请求中的文件名
  2. 正在 SFTP 服务器中搜索给定的文件名。
  3. 如果文件在 SFTP 服务器中可用,将其下载到名为“downloads”的文件夹中的本地路径
  4. 返回文件作为 FileResponse 的响应

我需要删除从 SFTP 下载的文件或删除下载文件夹中的所有内容。

实现此目标的最佳方法是什么? 在返回 FileResponse 之前执行异步 celery 任务怎么样?

解决此问题的一种方法是使用 Python 模块 tempfile,它提供临时文件,当删除 Python 中的所有引用时,这些文件会自动删除。

这是文档中的示例:

>>> 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()

获得此文件对象后,可以使用FileResponse将其发送回客户端。

另一种方法是使用 cronjob to delete files older than a certain number of days.