Tôi đã gặp sự cố tương tự và có thể giải quyết vấn đề này cho trường hợp của tôi. Đây là mã mà django sử dụng để xác định kích thước của một tập tin:
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
Do đó, django sẽ nâng cao một AttributeError
nếu tập tin không tồn tại trên đĩa (hoặc có một thuộc tính kích thước đã được xác định). Vì lớp TemporaryFile
cố gắng tạo tệp trong bộ nhớ thay vì thực sự trên đĩa, phương thức _get_size
này không hoạt động. Để có được nó để làm việc, tôi phải làm một cái gì đó như thế này:
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)
Ngoài ra (và tốt nhất), nếu bạn có thể tính toán kích thước của tập tin tạm thời bạn đang tạo, bạn có thể thiết lập một thuộc tính kích thước trên đối tượng TemporaryFile
trực tiếp. Do các thư viện tôi đang sử dụng, đây không phải là khả năng đối với tôi.
Nguồn
2011-11-26 22:00:16
Loại lỗi là gì? –
@john Đó là một AttributeError. – Conan