我想做一个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 "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提供的位置.
原文地址:https://www.jb51.cc/python/439726.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。