当前位置: 首页>>代码示例>>Python>>正文


Python MimeTypeDatabase.getMimeTypeForFile方法代码示例

本文整理汇总了Python中UM.MimeTypeDatabase.MimeTypeDatabase.getMimeTypeForFile方法的典型用法代码示例。如果您正苦于以下问题:Python MimeTypeDatabase.getMimeTypeForFile方法的具体用法?Python MimeTypeDatabase.getMimeTypeForFile怎么用?Python MimeTypeDatabase.getMimeTypeForFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在UM.MimeTypeDatabase.MimeTypeDatabase的用法示例。


在下文中一共展示了MimeTypeDatabase.getMimeTypeForFile方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: loadFromFile

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def loadFromFile(self, file_path: str) -> None:
        mime_type = MimeTypeDatabase.getMimeTypeForFile(file_path)

        item_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_path)))
        if not os.path.isfile(file_path):
            Logger.log("e", "[%s] is not a file", file_path)
            return None

        parser = ConfigParser(interpolation = None, allow_no_value = True)  # Accept options without any value,

        parser.read([file_path])
        if not parser.has_option("general", "name") or not parser.has_option("general", "weight"):
            return None

        settings = []  # type: List[str]
        for section in parser.sections():
            if section == "general":
                continue

            settings.append(section)
            for option in parser[section].keys():
                settings.append(option)
        self.setSettings(settings)
        self.setId(item_id)
        self.setName(parser["general"]["name"])
        self.setWeight(int(parser["general"]["weight"]))
开发者ID:TinkerGnome,项目名称:Cura,代码行数:28,代码来源:SettingVisibilityPreset.py

示例2: load

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def load(self):
        files = []
        for resource_type in self._resource_types:
            resources = Resources.getAllResourcesOfType(resource_type)

            try:
                resource_storage_path = Resources.getStoragePathForType(resource_type)
            except UnsupportedStorageTypeError:
                resource_storage_path = ""

            # Pre-process the list of files to insert relevant data
            # Most importantly, we need to ensure the loading order is DefinitionContainer, InstanceContainer, ContainerStack
            for path in resources:
                mime = MimeTypeDatabase.getMimeTypeForFile(path)
                container_type = self.__mime_type_map.get(mime.name)
                if not container_type:
                    Logger.log("w", "Could not determine container type for file %s, ignoring", path)
                    continue

                type_priority = 2

                if issubclass(container_type, DefinitionContainer.DefinitionContainer):
                    type_priority = 0

                if issubclass(container_type, InstanceContainer.InstanceContainer):
                    type_priority = 1

                # Since we have the mime type and resource type here, process these two properties so we do not
                # need to look up mime types etc. again.
                container_id = urllib.parse.unquote_plus(mime.stripExtension(os.path.basename(path)))
                read_only = os.path.dirname(path) != resource_storage_path

                files.append((type_priority, container_id, path, read_only, container_type))

        # Sort the list of files by type_priority so we can ensure correct loading order.
        files = sorted(files, key = lambda i: i[0])

        for _, container_id, file_path, read_only, container_type in files:
            if container_id in self._id_container_cache:
                continue

            try:
                if issubclass(container_type, DefinitionContainer.DefinitionContainer):
                    definition = self._loadCachedDefinition(container_id, file_path)
                    if definition:
                        self.addContainer(definition)
                        continue

                new_container = container_type(container_id)
                with open(file_path, encoding = "utf-8") as f:
                    new_container.deserialize(f.read())
                new_container.setReadOnly(read_only)

                if issubclass(container_type, DefinitionContainer.DefinitionContainer):
                    self._saveCachedDefinition(new_container)

                self.addContainer(new_container)
            except Exception as e:
                Logger.logException("e", "Could not deserialize container %s", container_id)
开发者ID:TimurAykutYildirim,项目名称:Uranium,代码行数:61,代码来源:ContainerRegistry.py

示例3: _pathToMime

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
 def _pathToMime(self, path: str) -> Optional[MimeType]:
     try:
         mime = MimeTypeDatabase.getMimeTypeForFile(path)
     except MimeTypeDatabase.MimeTypeNotFoundError:
         Logger.log("w", "MIME type could not be found for file: {path}, ignoring it.".format(path = path))
         return None
     if mime.name not in ContainerRegistry.mime_type_map:  # The MIME type is known, but it's not a container.
         return None
     return mime
开发者ID:Ultimaker,项目名称:Uranium,代码行数:11,代码来源:LocalContainerProvider.py

示例4: convertPathToId

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
 def convertPathToId(path: str) -> str:
     mime = None
     try:
         mime = MimeTypeDatabase.getMimeTypeForFile(path)
     except MimeTypeDatabase.MimeTypeNotFoundError:
         pass
     if mime:
         return urllib.parse.unquote_plus(mime.stripExtension(os.path.basename(path)))
     else:
         return ""
开发者ID:Ultimaker,项目名称:Uranium,代码行数:12,代码来源:PackageManager.py

示例5: exportContainer

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
        if not container_id or not file_type or not file_url_or_string:
            return { "status": "error", "message": "Invalid arguments"}

        if isinstance(file_url_or_string, QUrl):
            file_url = file_url_or_string.toLocalFile()
        else:
            file_url = file_url_or_string

        if not file_url:
            return { "status": "error", "message": "Invalid path"}

        mime_type = None
        if not file_type in self._container_name_filters:
            try:
                mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
            except MimeTypeNotFoundError:
                return { "status": "error", "message": "Unknown File Type" }
        else:
            mime_type = self._container_name_filters[file_type]["mime"]

        containers = self._container_registry.findContainers(None, id = container_id)
        if not containers:
            return { "status": "error", "message": "Container not found"}
        container = containers[0]

        if Platform.isOSX() and "." in file_url:
            file_url = file_url[:file_url.rfind(".")]

        for suffix in mime_type.suffixes:
            if file_url.endswith(suffix):
                break
        else:
            file_url += "." + mime_type.preferredSuffix

        if not Platform.isWindows():
            if os.path.exists(file_url):
                result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
                                              catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url))
                if result == QMessageBox.No:
                    return { "status": "cancelled", "message": "User cancelled"}

        try:
            contents = container.serialize()
        except NotImplementedError:
            return { "status": "error", "message": "Unable to serialize container"}

        if contents is None:
            return {"status": "error", "message": "Serialization returned None. Unable to write to file"}

        with SaveFile(file_url, "w") as f:
            f.write(contents)

        return { "status": "success", "message": "Succesfully exported container", "path": file_url}
开发者ID:daid,项目名称:Cura,代码行数:56,代码来源:ContainerManager.py

示例6: _populate

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def _populate(self):
        from cura.CuraApplication import CuraApplication
        items = []
        for file_path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.SettingVisibilityPreset):
            try:
                mime_type = MimeTypeDatabase.getMimeTypeForFile(file_path)
            except MimeTypeNotFoundError:
                Logger.log("e", "Could not determine mime type of file %s", file_path)
                continue

            item_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_path)))
            if not os.path.isfile(file_path):
                Logger.log("e", "[%s] is not a file", file_path)
                continue

            parser = ConfigParser(allow_no_value = True)  # accept options without any value,
            try:
                parser.read([file_path])
                if not parser.has_option("general", "name") or not parser.has_option("general", "weight"):
                    continue

                settings = []
                for section in parser.sections():
                    if section == 'general':
                        continue

                    settings.append(section)
                    for option in parser[section].keys():
                        settings.append(option)

                items.append({
                    "id": item_id,
                    "name": catalog.i18nc("@action:inmenu", parser["general"]["name"]),
                    "weight": parser["general"]["weight"],
                    "settings": settings,
                })

            except Exception:
                Logger.logException("e", "Failed to load setting preset %s", file_path)

        items.sort(key = lambda k: (int(k["weight"]), k["id"]))
        # Put "custom" at the top
        items.insert(0, {"id": "custom",
                         "name": "Custom selection",
                         "weight": -100,
                         "settings": []})

        self.setItems(items)
开发者ID:Twosilly,项目名称:Cura,代码行数:50,代码来源:SettingVisibilityPresetsModel.py

示例7: _sendMaterials

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def _sendMaterials(self, materials_to_send: Set[str]) -> None:
        file_paths = Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.MaterialInstanceContainer)

        # Find all local material files and send them if needed.
        for file_path in file_paths:
            try:
                mime_type = MimeTypeDatabase.getMimeTypeForFile(file_path)
            except MimeTypeDatabase.MimeTypeNotFoundError:
                continue

            file_name = os.path.basename(file_path)
            material_id = urllib.parse.unquote_plus(mime_type.stripExtension(file_name))
            if material_id not in materials_to_send:
                # If the material does not have to be sent we skip it.
                continue

            self._sendMaterialFile(file_path, file_name, material_id)
开发者ID:rwreynolds,项目名称:Cura,代码行数:19,代码来源:SendMaterialJob.py

示例8: setBaseName

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def setBaseName(self, base_name: str, is_project_file: bool = False) -> None:
        self._is_user_specified_job_name = False

        # Ensure that we don't use entire path but only filename
        name = os.path.basename(base_name)

        # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
        # extension. This cuts the extension off if necessary.
        check_name = os.path.splitext(name)[0]
        filename_parts = os.path.basename(base_name).split(".")

        # If it's a gcode, also always update the job name
        is_gcode = False
        if len(filename_parts) > 1:
            # Only check the extension(s)
            is_gcode = "gcode" in filename_parts[1:]

        # if this is a profile file, always update the job name
        # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
        is_empty = check_name == ""
        if is_gcode or is_project_file or (is_empty or (self._base_name == "" and self._base_name != check_name)):
            # Only take the file name part, Note : file name might have 'dot' in name as well

            data = ""
            try:
                mime_type = MimeTypeDatabase.getMimeTypeForFile(name)
                data = mime_type.stripExtension(name)
            except MimeTypeNotFoundError:
                Logger.log("w", "Unsupported Mime Type Database file extension %s", name)

            if data is not None and check_name is not None:
                self._base_name = data
            else:
                self._base_name = ""

            # Strip the old "curaproject" extension from the name
            OLD_CURA_PROJECT_EXT = ".curaproject"
            if self._base_name.lower().endswith(OLD_CURA_PROJECT_EXT):
                self._base_name = self._base_name[:len(self._base_name) - len(OLD_CURA_PROJECT_EXT)]

            # CURA-5896 Try to strip extra extensions with an infinite amount of ".curaproject.3mf".
            OLD_CURA_PROJECT_3MF_EXT = ".curaproject.3mf"
            while self._base_name.lower().endswith(OLD_CURA_PROJECT_3MF_EXT):
                self._base_name = self._base_name[:len(self._base_name) - len(OLD_CURA_PROJECT_3MF_EXT)]

            self._updateJobName()
开发者ID:Ultimaker,项目名称:Cura,代码行数:48,代码来源:PrintInformation.py

示例9: importMaterialContainer

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def importMaterialContainer(self, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
        if not file_url_or_string:
            return {"status": "error", "message": "Invalid path"}

        if isinstance(file_url_or_string, QUrl):
            file_url = file_url_or_string.toLocalFile()
        else:
            file_url = file_url_or_string

        if not file_url or not os.path.exists(file_url):
            return {"status": "error", "message": "Invalid path"}

        try:
            mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
        except MimeTypeNotFoundError:
            return {"status": "error", "message": "Could not determine mime type of file"}

        container_type = self._container_registry.getContainerForMimeType(mime_type)
        if not container_type:
            return {"status": "error", "message": "Could not find a container to handle the specified file."}

        container_id = urllib.parse.unquote_plus(mime_type.stripExtension(os.path.basename(file_url)))
        container_id = self._container_registry.uniqueName(container_id)

        container = container_type(container_id)

        try:
            with open(file_url, "rt", encoding = "utf-8") as f:
                container.deserialize(f.read())
        except PermissionError:
            return {"status": "error", "message": "Permission denied when trying to read the file."}
        except ContainerFormatError:
            return {"status": "error", "Message": "The material file appears to be corrupt."}
        except Exception as ex:
            return {"status": "error", "message": str(ex)}

        container.setDirty(True)

        self._container_registry.addContainer(container)

        return {"status": "success", "message": "Successfully imported container {0}".format(container.getName())}
开发者ID:TinkerGnome,项目名称:Cura,代码行数:43,代码来源:ContainerManager.py

示例10: load

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
    def load(self) -> None:
        files = []
        old_file_expression = re.compile(r"\{sep}old\{sep}\d+\{sep}".format(sep = os.sep))

        for resource_type in self._resource_types:
            resources = Resources.getAllResourcesOfType(resource_type)

            try:
                resource_storage_path = Resources.getStoragePathForType(resource_type)
            except UnsupportedStorageTypeError:
                resource_storage_path = ""

            # Pre-process the list of files to insert relevant data
            # Most importantly, we need to ensure the loading order is DefinitionContainer, InstanceContainer, ContainerStack
            for path in resources:
                if old_file_expression.search(path):
                    # This is a backup file, ignore it.
                    continue

                try:
                    mime = MimeTypeDatabase.getMimeTypeForFile(path)
                except MimeTypeDatabase.MimeTypeNotFoundError:
                    # No valid mime type found for file, ignore it.
                    continue

                container_type = self.__mime_type_map.get(mime.name)
                if not container_type:
                    Logger.log("w", "Could not determine container type for file %s, ignoring", path)
                    continue

                type_priority = container_type.getLoadingPriority()

                # Since we have the mime type and resource type here, process these two properties so we do not
                # need to look up mime types etc. again.
                container_id = urllib.parse.unquote_plus(mime.stripExtension(os.path.basename(path)))
                read_only = os.path.realpath(os.path.dirname(path)) != os.path.realpath(resource_storage_path)

                files.append((type_priority, container_id, path, read_only, container_type))

        # Sort the list of files by type_priority so we can ensure correct loading order.
        files = sorted(files, key = lambda i: i[0])
        resource_start_time = time.time()
        for _, container_id, file_path, read_only, container_type in files:
            if container_id in self._id_container_cache:
                Logger.log("c", "Found a container with a duplicate ID: %s", container_id)
                Logger.log("c", "Existing container is %s, trying to load %s from %s", self._id_container_cache[container_id], container_type, file_path)
                continue

            try:
                if issubclass(container_type, DefinitionContainer):
                    definition = self._loadCachedDefinition(container_id, file_path)
                    if definition:
                        self.addContainer(definition)
                        continue

                new_container = container_type(container_id)
                with open(file_path, encoding = "utf-8") as f:
                    new_container.deserialize(f.read())
                new_container.setReadOnly(read_only)
                new_container.setPath(file_path)

                if issubclass(container_type, DefinitionContainer):
                    self._saveCachedDefinition(new_container)

                self.addContainer(new_container)
            except Exception as e:
                Logger.logException("e", "Could not deserialize container %s", container_id)
        Logger.log("d", "Loading data into container registry took %s seconds", time.time() - resource_start_time)
开发者ID:senttech,项目名称:Uranium,代码行数:70,代码来源:ContainerRegistry.py

示例11: _stripFileToId

# 需要导入模块: from UM.MimeTypeDatabase import MimeTypeDatabase [as 别名]
# 或者: from UM.MimeTypeDatabase.MimeTypeDatabase import getMimeTypeForFile [as 别名]
 def _stripFileToId(self, file):
     mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
     file = mime_type.stripExtension(file)
     return file.replace("Cura/", "")
开发者ID:daid,项目名称:Cura,代码行数:6,代码来源:ThreeMFWorkspaceReader.py


注:本文中的UM.MimeTypeDatabase.MimeTypeDatabase.getMimeTypeForFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。