我想做一个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 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 "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提供的位置.