def _secure_folder_path(folderpath, skip_existing, keep_unicode): """ Splits a folder path, runs each component through the secure_filename function, and returns the reconstituted folder path. If skip_existing is True, components of the path that already exist will not be modified. Raises a ValueError if any of the path components becomes empty. """ _, _, f_list = filepath_components(add_sep(folderpath)) built_path = '' for component in f_list: if component: next_path = os.path.join(built_path, component) if not skip_existing or not path_exists(next_path, require_directory=True): try: component = secure_filename(component, keep_unicode) except ValueError as e: raise ValueError(unicode(e) + u': ' + component) built_path = os.path.join(built_path, component) return built_path
def _get_nearest_parent_folder(rel_path, data_manager, db_session): """ Returns the nearest active parent folder object for rel_path that already exists in the database. E.g. For rel_path a/b/c/d If the database contains all folders then c is returned. If the database contains only a and b so far then b is returned. If no folders in rel_path exist then the root folder is returned. Raises a DBError if no parent folder can be found at all (but this should never happen). """ # Convert a/b/c/d to ['a','b','c','d'] _, _, f_list = filepath_components(add_sep(rel_path)) # Start at root folder try_path = '' db_parent_folder = data_manager.get_folder( folder_path=try_path, _db_session=db_session ) # Then try to get more specific if len(f_list) > 1: # Loop to len-1 to stop at c in a/b/c/d for idx in range(len(f_list) - 1): try_path += (os.path.sep + f_list[idx]) db_f = data_manager.get_folder( folder_path=try_path, _db_session=db_session ) if db_f and db_f.status == Folder.STATUS_ACTIVE: db_parent_folder = db_f else: break # db_parent_folder should at least be the root folder if not db_parent_folder: raise DBError('Failed to identify a parent folder for: ' + rel_path) return db_parent_folder