【问题标题】:How to handle file delete after returning it has response in Django rest framework返回文件后如何处理文件删除在Django rest框架中有响应
【发布时间】:2021-12-28 18:08:32
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你试过什么?您可以使用 os.remove(file_path) 删除文件
  • @shivankgtm 我知道,但如果我在返回 FileResponse 之前这样做,文件会被删除吗?

标签: python django django-rest-framework django-views


【解决方案1】:

解决这个问题的一种方法是使用 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 删除文件older than a certain number of days

【讨论】:

  • 很好,如果我们自己写一个文件并且只针对 tempfile(python) 继续向其中写入数据会有什么不同吗?
  • @shivankgtm 您可以像使用 open() 创建的文件对象一样使用 tempfile 创建的文件对象。如果您还需要文件具有名称,则需要 NamedTemporaryFile。
  • 有什么特殊的命令可以创建临时文件吗?
  • @SivaPerumal 我添加了一个关于如何创建临时文件的代码示例。
  • @SivaPerumal 1) 你给 FileResponse 临时文件。例如FileResponse(temp_file)。 2)如果关闭文件,它将被删除。所以不要关闭文件。 FileResponse 将关闭文件。 FileResponse 文档说,“文件将自动关闭”
猜你喜欢
  • 2014-10-16
  • 2023-03-23
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多