python – Django:如何允许可疑文件操作/复制文件

我想做一个SusjicIoUsFileOperation,认情况下django不允许.

我正在编写一个命令(通过manage.py importfiles运行),在我自己编写的Django文件存储库中导入真实文件系统上的给定目录结构.

我想,这是我的相关代码

def _handle_directory(self,directory_path,directory):
    for root,subFolders,files in os.walk(directory_path):
        for filename in files:
            self.cnt_files += 1
            new_file = File(directory=directory,filename=filename,file=os.path.join(root,filename),uploader=self.uploader)
            new_file.save()

回溯是:

Traceback (most recent call last):
  File ".\manage.py",line 10,in __init__.py",line 399,in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py",line 392,in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py",line 242,in run_from_argv
    self.execute(*args,**options.__dict__)
  File "C:\Python27\lib\site-packages\django\core\management\base.py",line 285,in execute
    output = self.handle(*args,**options)
  File "D:\Development\github\Palco\engine\filestorage\management\commands\importfiles.py",line 53,in handle
    self._handle_directory(args[0],root)
  File "D:\Development\github\Palco\engine\filestorage\management\commands\importfiles.py",line 63,in _handle_directory
    new_file.save()
  File "D:\Development\github\Palco\engine\filestorage\models.py",line 157,in save
    self.sha512 = hashlib.sha512(self.file.read()).hexdigest()
  File "C:\Python27\lib\site-packages\django\core\files\utils.py",line 16,in IoUsFileOperation("Attempted access to '%s' denied." % name)
django.core.exceptions.SuspicIoUsFileOperation: Attempted access to 'D:\Temp\importme\readme.html' denied.

full model can be found at GitHub. full command is currently on gist.github.com available.

如果您不想检查模型:我的File类的属性文件FileField.

我假设,这个问题发生了,因为我只是“链接”到找到的文件.但是我需要复制它,对吧?如何将文件复制到文件中?

最佳答案
分析堆栈跟踪的这一部分:

File "C:\Python27\lib\site-packages\django\core\files\storage.py",in path
    raise SuspicIoUsFileOperation("Attempted access to '%s' denied." % name)

导致标准的Django FileSystemStorage.它希望文件在您的MEDIA_ROOT中.您的文件可以在文件系统中的任何位置,因此会出现此问题.

您应该传递类文件对象而不是文件模型的路径.实现这一目标的最简单方法是使用Django File类,它是python文件类对象的包装器.有关详细信息,请参见File object documentation.

更新:

好的,我在这里建议从文档中获取的路线:

from django.core.files import File as FileWrapper

...

path = os.path.join(root,filename)
with open(path,'r') as f:
    file_wrapper = FileWrapper(f)
    new_file = File(directory=directory,file=file_wrapper,uploader=self.uploader)
    new_file.save()

如果它工作,它应该将文件复制到您的secure_storage callable提供的位置.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...