“Upload” a file from django shell

2020-02-23 07:19发布

问题:

I need to import some data from a excel file and a folder with images, every row in the excel describes every entry and have a list of filenames in the folder (photos related to the entry).

I've done a script which creates every entry in the database and saves it trough the django shell, but i have no idea how to instantiate a InMemoryUploadedFile for save it with the model.

In django 1.0 I had this small class which allowed me to do what i need, but with changes in django 1.1 it's not working any more.

class ImportFile(file):
    def __init__(self, *args, **kwargs):
        super(ImportFile, self).__init__(*args, **kwargs)
        self._file = self
        self.size = os.path.getsize(self.name)

    def __len__(self):
        return self.size

    def chunks(self, chunk_size=None):
        self._file.seek(0)
        yield self.read()

I was using this class with this piece of code to load images and saving them with the model instance.

for photo in photos:
    f = ImportFile(os.path.join(IMPORT_DIR, 'fotos', photo), 'r')
    p = Photo(name=f.name, image=f, parent=supply.supply_ptr)
    name = str(uuid1()) + os.path.splitext(f.name)[1]
    p.image.save(name, f)
    p.save()

The question is, how do I create a InMemoryUploadedFile or TemporaryUploadedFile from a file in python?, or any other thing that could work in this context.

回答1:

Finally I found the answer.

from django.core.files import File

f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'r'))
p = Photo(name=f.name, image=f, parent=supply.supply_ptr)
name = str(uuid1()) + os.path.splitext(f.name)[1]
p.image.save(name, f)
p.save()


回答2:

If using Python 3 one adjustment is needed - change 'r' to 'rb':

f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'rb'))