Django"无法确定文件的大小"错误与tempfile.TemporaryFile

Con*_*nan 9 python django

我遇到标准Django FileField和tempfile.TemporaryFile的问题.每当我尝试使用TemporaryFile保存FileField时,我都会收到"无法确定文件大小"错误.

例如,给定名为Model的模型,名为FileField的文件字段和名为TempFile的临时文件:

Model.FileField.save('foobar', django.core.files.File(TempFile), save=True)
Run Code Online (Sandbox Code Playgroud)

这将给我上述错误.有什么想法吗?

sha*_*unc 11

我有这个问题tempfile.TemporaryFile.当我切换到tempfile.NamedTemporaryFile它时就消失了.我相信TemporaryFile只是模拟成为一个文件(至少在某些操作系统上),而NamedTemporaryFile实际上是一个文件.


Ste*_*ley 2

我遇到了同样的问题,并且能够为我的案例解决它。这是 django 用于确定文件大小的代码:


def _get_size(self):
  if not hasattr(self,  '_size'):
    if hasattr(self.file, 'size'):
      self._size = self.file.size
    elif os.path.exists(self.file.name):
      self._size = os.path.getsize(self.file.name)
    else:
      raise AttributeError("Unable to determine the file's size.")
  return self._size

AttributeError因此,如果磁盘上不存在该文件(或者已经定义了大小属性),django 将引发。由于该类TemporaryFile尝试在内存中而不是实际在磁盘上创建文件,因此此_get_size方法不起作用。为了让它工作,我必须做这样的事情:


import tempfile, os
# Use tempfile.mkstemp, since it will actually create the file on disk.
(temp_filedescriptor, temp_filepath) = tempfile.mkstemp()
# Close the open file using the file descriptor, since file objects
# returned by os.fdopen don't work, either
os.close(temp_filedescriptor)

# Open the file on disk
temp_file = open(temp_filepath, "w+b")

# Do operations on your file here . . .

modelObj.fileField.save("filename.txt", File(temp_file))

temp_file.close()
# Remove the created file from disk.
os.remove(temp_filepath)

或者(最好),如果您可以计算正在创建的临时文件的大小,则可以TemporaryFile直接在对象上设置大小属性。由于我使用的库,这对我来说是不可能的。