2011-07-22 22 views
9

Tôi đang gặp sự cố với chuẩn Django FileField và tempfile.TemporaryFile. Bất cứ khi nào tôi cố gắng lưu một FileField với TemporaryFile, tôi nhận được lỗi "Không thể xác định kích thước của tệp".Django "Không thể xác định kích thước của tệp" lỗi với tempfile.TemporaryFile

Ví dụ, đưa ra một mô hình mang tên Model, một filefield tên FileField, và một temporaryfile tên TempFile:

Model.FileField.save('foobar', django.core.files.File(TempFile), save=True) 

này sẽ cung cấp cho tôi những lỗi nói trên. Có suy nghĩ gì không?

+0

Loại lỗi là gì? –

+0

@john Đó là một AttributeError. – Conan

Trả lời

2

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.

11

Tôi gặp sự cố này với tempfile.TemporaryFile. Khi tôi chuyển sang tempfile.NamedTemporaryFile nó đã biến mất. Tôi tin rằng TemporaryFile chỉ mô phỏng là một tệp (trên một số hệ điều hành ít nhất), trong khi NamedTemporaryFile thực sự là một tệp.

2

Tôi có vấn đề này trên Heroku ngay cả với tempfile.NamedTemporaryFile và đã khá thất vọng ...

Tôi giải quyết nó sử dụng lời khuyên của Steven bằng cách thiết lập kích thước tùy ý bằng tay (có, bẩn thỉu, nhưng công việc cho tôi):

from django.core.files import File 
from django.core.files.temp import NamedTemporaryFile 

img_temp = NamedTemporaryFile() 
# Do your stuffs ... 
img_temp.flush() 
img_temp.size = 1024 

media.thumbnail.save('dummy', File(img_temp)) 

Cảm ơn!

Các vấn đề liên quan