def _handle_directory(self, directory_path, directory): for fs_name in os.listdir(directory_path): fs_path = os.path.join(directory_path, fs_name) if os.path.isfile(fs_path): with open(fs_path, 'rb') as f: file_wrapper = File(f) self.cnt_files += 1 new_file = FsFile(directory=directory, filename=fs_name.decode(self.fs_encoding).encode('utf-8'), file=file_wrapper, uploader=self.uploader) new_file.save() self.total_size += new_file.get_size() if os.path.isdir(fs_path): self.cnt_directories += 1 new_directory = Directory(name=fs_name, parent=directory, owner=self.owner) new_directory.save() self._handle_directory(fs_path, new_directory)
def handle(self, *args, **options): if len(args) != 1: raise CommandError('Expected a directory as an argument') if not os.path.exists(args[0]): raise CommandError('Directory %s does not exists' % args[0]) try: self.uploader = Actor.objects.get(pk=options['uploader']) self.owner = Group.objects.get(pk=options['owner']) except Actor.DoesNotExist: raise CommandError('%s is not a valid user id' % options['uploader']) except Group.DoesNotExist: raise CommandError('%s is not a valid group id' % options['group']) root = Directory(name='Import %s' % datetime.now(), parent=None, owner=self.owner) root.save() self._handle_directory(args[0], root) total_size = filesizeformat(self.total_size) self.stdout.write(u'Successfully imported %d files in %d directories, with a total size of %s.' % ( self.cnt_files, self.cnt_directories, total_size))