Avoid copying when adding a large file to FileField

陌路散爱 提交于 2020-01-05 04:41:12

问题


I'm dealing with some quite large files which are uncomfortable to upload via http, so my users upload files using FTP which my code then needs to move into FileField.upload_to (where they normally end up when uploaded via HTTP). My problem is, the commonly suggested method of using django.core.files.File:

from django.core.files import File

# filename is a FileField
file_obj = MyModel(filename=File(open('VIDEO_TS.tar', 'rb')))

leads to copying the data, which i need to avoid. Is there any way to add the already existing file to a FileField while making sure upload_to is called?


回答1:


I'd say that easiest way would be writing your own field or storage.




回答2:


a bit late, but:

class _ExistingFile(UploadedFile):
    """ Utility class for importing existing files to FileField's. """

    def __init__(self, path, *args, **kwargs):
        self.path = path
        super(_ExistingFile, self).__init__(*args, **kwargs)

    def temporary_file_path(self):
        return self.path

    def close(self):
        pass

    def __len__(self):
        return 0

usage:

my_model.file_field.save(upload_to, _ExistingFile('VIDEO_TS.tar'))


来源:https://stackoverflow.com/questions/1300033/avoid-copying-when-adding-a-large-file-to-filefield

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!