Python get mime type

34 Python code examples are found related to " get mime type". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: dev_appserver.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def GetMimeType(self, path):
    """Returns the mime type that we should use when serving the specified file.

    Args:
      path: A string containing the file's path relative to the app.

    Returns:
      String containing the mime type to use. Will be 'application/octet-stream'
      if we have no idea what it should be.
    """
    url_map = self._FirstMatch(path)
    if url_map.mime_type is not None:
      return url_map.mime_type


    unused_filename, extension = os.path.splitext(path)
    return mimetypes.types_map.get(extension, 'application/octet-stream') 
Example 2
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
def get_mime_type(resource):
    import magic
    if resource.startswith('file://'):
        resource = resource[len('file://'):]

    if resource.startswith('http://') or resource.startswith('https://'):
        with urllib.request.urlopen(resource) as response:
            return response.info().get_content_type()
    else:
        if hasattr(magic, 'detect_from_filename'):
            mime = magic.detect_from_filename(resource)
        elif hasattr(magic, 'from_file'):
            mime = magic.from_file(resource, mime=True)
        else:
            raise RuntimeError('The installed magic version provides neither detect_from_filename nor from_file')

        if mime:
            return mime.mime_type 
Example 3
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def get_mime_type(
        self, credential_id: str, attr: str = None
    ) -> Union[dict, str]:
        """
        Get MIME type per attribute (or for all attributes).

        Args:
            credential_id: credential id
            attr: attribute of interest or omit for all

        Returns: Attribute MIME type or dict mapping attribute names to MIME types
            attr_meta_json = all_meta.tags.get(attr)

        """
        try:
            mime_types_record = await IndyStorage(self.wallet).get_record(
                IndyHolder.RECORD_TYPE_MIME_TYPES,
                f"{IndyHolder.RECORD_TYPE_MIME_TYPES}::{credential_id}",
            )
        except StorageError:
            return None  # no MIME types: not an error

        return mime_types_record.tags.get(attr) if attr else mime_types_record.tags 
Example 4
Source File: MimeTypeDatabase.py    From Uranium with GNU Lesser General Public License v3.0 6 votes vote down vote up
def getMimeType(cls, name: str) -> MimeType:
        """Get a MIME type by name.

        This will return a ``MimeType`` object corresponding to the specified
        name.

        :param name: The name of the MIME type to return.
        :return: A ``MimeType`` object corresponding to the specified name.
        :exception MimeTypeNotFoundError Raised when the specified MIME type
        cannot be found.
        """

        for custom_mime in cls.__custom_mimetypes:
            if custom_mime.name == name:
                return custom_mime

        mime = cls.__system_database.mimeTypeForName(name)
        if mime.isValid():
            return MimeType.fromQMimeType(mime)

        raise MimeTypeNotFoundError("Could not find mime type named {0}".format(name)) 
Example 5
Source File: pathsutils.py    From BlackSheep with MIT License 5 votes vote down vote up
def get_mime_type(file_name: str) -> str:
    extension = get_file_extension_from_name(file_name)
    mime_type = mime.guess_type(file_name)[0] or DEFAULT_MIME

    if mime_type == DEFAULT_MIME and extension in MIME_BY_EXTENSION:
        mime_type = MIME_BY_EXTENSION.get(extension)

    return mime_type 
Example 6
Source File: __init__.py    From micropython-samples with MIT License 5 votes vote down vote up
def get_mime_type(fname):
    # Provide minimal detection of important file
    # types to keep browsers happy
    if fname.endswith(".html"):
        return "text/html"
    if fname.endswith(".css"):
        return "text/css"
    if fname.endswith(".png") or fname.endswith(".jpg"):
        return "image"
    return "text/plain" 
Example 7
Source File: pathsutils.py    From BlackSheep with MIT License 5 votes vote down vote up
def get_best_mime_type(file_name: str) -> Tuple[str, str]:
    extension = get_file_extension_from_name(file_name)
    mime_type = mime.guess_type(file_name)[0] or DEFAULT_MIME

    if mime_type == DEFAULT_MIME and extension in MIME_BY_EXTENSION:
        mime_type = MIME_BY_EXTENSION.get(extension)

    return extension, mime_type 
Example 8
Source File: mobi.py    From kmanga with GNU General Public License v3.0 5 votes vote down vote up
def get_image_mime_type(self, number):
        """Get image MIME type."""
        image_path = self.get_image_path(number)
        _, ext = os.path.splitext(image_path.lower())
        mime_type = {
            '.jpg': 'image/jpeg',
            '.png': 'image/png',
        }
        return mime_type[ext] 
Example 9
Source File: icon.py    From ubuntu-cleaner with GNU General Public License v3.0 5 votes vote down vote up
def get_from_mime_type(mime, size=DEFAULT_SIZE):
    try:
        gicon = Gio.content_type_get_icon(mime)

        return get_from_list(gicon.get_names(), size=size)
    except Exception as e:
        log.error('get_from_mime_type failed: %s' % e)
        return get_from_name(size=size) 
Example 10
Source File: deploy_documentation.py    From flambe with MIT License 5 votes vote down vote up
def get_mime_type(path):
    mimetype, _ = mimetypes.guess_type(path)
    if mimetype is None:
        raise Exception("Failed to guess mimetype")
    return mimetype 
Example 11
Source File: audiotools.py    From kur with Apache License 2.0 5 votes vote down vote up
def get_mime_type(filename):
	""" Returns the MIME type associated with a particular audio file.
	"""
	try:
		import magic
	except ImportError:
		if get_mime_type.warn:
			logger.warning('Python package "magic" could not be loaded, '
				'possibly because system library "libmagic" could not be '
				'found. We are falling back on our own heuristics.')
			get_mime_type.warn = False

		ext = os.path.splitext(filename)[1].lower()
		return {
			'.wav' : 'audio/x-wav',
			'.mp3' : 'audio/mpeg',
			'.flac' : 'audio/x-flac'
		}.get(ext, 'unknown')
	else:
		# Read off magic numbers and return MIME types
		mime_magic = magic.Magic(mime=True)
		ftype = mime_magic.from_file(filename)
		if isinstance(ftype, bytes):
			ftype = ftype.decode('utf-8')

		# If we are dealing with a symlink, read the link
		# and try again with the target file.  We do this in 
		# a while loop to cover the case of symlinks which
		# point to other symlinks
		current_filename = filename
		while ftype == 'inode/symlink':
			current_filename = os.readlink(current_filename)
			ftype = mime_magic.from_file(current_filename)
			ftype = ftype.decode('utf-8') if isinstance(ftype, bytes) else ftype
			
		return ftype 
Example 12
Source File: multipart.py    From laniakea with Mozilla Public License 2.0 5 votes vote down vote up
def get_mime_type(path, default='text/plain'):
        with open(path, 'rb') as fo:
            line = fo.readline()
        mime_type = default
        for shebang in MultipartUserData.MIME:
            if line.startswith(shebang):
                mime_type = MultipartUserData.MIME[shebang]
                break
        return mime_type.split('/', 1) 
Example 13
Source File: base.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def get_mime_type(cls):
        """
        Get a string representing the MIME data type that this class is meant to parse.
        :return: A string representing the MIME data type that this class is meant to parse.
        """
        raise NotImplementedError("Subclasses must implement this!")

    # Public Methods 
Example 14
Source File: fs_utils.py    From python-aria-mirror-bot with GNU General Public License v3.0 5 votes vote down vote up
def get_mime_type(file_path):
    mime = magic.Magic(mime=True)
    mime_type = mime.from_file(file_path)
    mime_type = mime_type if mime_type else "text/plain"
    return mime_type 
Example 15
Source File: utils.py    From virt-bootstrap with GNU General Public License v3.0 5 votes vote down vote up
def get_mime_type(path):
    """
    Get the mime type of a file.
    """
    proc = subprocess.Popen(
        ["/usr/bin/file", "--mime-type", path],
        stdout=subprocess.PIPE
    )
    proc.wait()
    with proc.stdout as output:
        return output.read().decode('utf-8').split()[1] 
Example 16
Source File: gltf_reader.py    From compas with MIT License 5 votes vote down vote up
def get_mime_type(self, string):
        if string is None or not self.is_data_uri(string):
            return None
        pattern = r'data:([\w/]+)(?<![;,])'
        result = re.search(pattern, string)
        return result.group(1) 
Example 17
Source File: CommonUtils.py    From alipay-sdk-python-all with Apache License 2.0 5 votes vote down vote up
def get_mime_type(bs):
    suffix = get_file_suffix(bs)
    mime_type = "application/octet-stream"
    if suffix == "JPG":
        mime_type = "image/jpeg"
    elif suffix == "GIF":
        mime_type = "image/gif"
    elif suffix == "PNG":
        mime_type = "image/png"
    elif suffix == "BMP":
        mime_type = "image/bmp"
    return mime_type 
Example 18
Source File: motion_event.py    From motion-notify with GNU General Public License v3.0 5 votes vote down vote up
def get_mime_type(self):
        if self.media_file.endswith(("jpg", "png", "gif", "bmp")):
            return "image/" + self.file_type
        else:
            return "video/" + self.file_type 
Example 19
Source File: util.py    From blobxfer with MIT License 5 votes vote down vote up
def get_mime_type(filename):
    # type: (str) -> str
    """Guess the type of a file based on its filename
    :param str filename: filename to guess the content-type
    :rtype: str
    :rturn: string of form 'class/type' for MIME content-type header
    """
    # TODO extract encoding for ContentEncoding property
    return mimetypes.guess_type(filename)[0] or _DEFAULT_MIME_TYPE 
Example 20
Source File: microWebSrv2.py    From MicroWebSrv2 with MIT License 5 votes vote down vote up
def GetMimeTypeFromFilename(filename) :
        filename = filename.lower()
        for ext in MicroWebSrv2._MIME_TYPES :
            if filename.endswith(ext) :
                return MicroWebSrv2._MIME_TYPES[ext]
        return None

    # ------------------------------------------------------------------------ 
Example 21
Source File: recipe-578771.py    From code with MIT License 5 votes vote down vote up
def getMimeType(self, filePath):
        #fileUrl      = urllib.pathname2url(filePath)
        fileUrl      = "file:///{0}".format(filePath)
        fileMimeType = mimetypes.guess_type(fileUrl)[0]

        return (
            False
            if fileMimeType == None
            else fileMimeType.split("/")[0]
        ) 
Example 22
Source File: tasks.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_mime_type(file_name):
        mime_type, _ = mimetypes.guess_type(file_name)
        if mime_type is None:
            mime_type = 'application/text'
        return mime_type 
Example 23
Source File: notifications.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_predefined_mime_type(rfn: str) -> Optional[str]:
    fn = os.path.normpath(os.path.join(settings.NOTIFICATION_CUSTOM_TEMPLATES_PATH_IN_MEDIA, rfn))
    _, file_extension = os.path.splitext(fn)
    if file_extension.lower() == '.svg':
        return 'svg+xml'
    return None 
Example 24
Source File: FileHandler.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getWriterByMimeType(self, mime: str) -> Optional["FileWriter"]:
        """Get a mesh writer object that supports writing the specified mime type

        :param mime: The mime type that should be supported.
        :return: A FileWriter instance or None if no mesh writer supports the specified mime type. If there are multiple
        writers that support the specified mime type, the first entry is returned.
        """

        writer_data = PluginRegistry.getInstance().getAllMetaData(filter={self._writer_type: {}}, active_only=True)
        for entry in writer_data:
            for output in entry[self._writer_type].get("output", []):
                if mime == output["mime_type"]:
                    return self._writers[entry["id"]]

        return None 
Example 25
Source File: MimeTypeDatabase.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getMimeTypeForFile(cls, file_name: str) -> MimeType:
        """Get a MIME type for a specific file.

        :param file_name: The name of the file to get the MIME type for.
        :return: A MimeType object that contains the detected MIME type for the file.
        :exception MimeTypeNotFoundError Raised when no MIME type can be found
            for the specified file.
        """

        # Properly normalize the file name to only be the base name of a path if we pass a path.
        file_name = os.path.basename(file_name)

        matches = []  # type: List[MimeType]
        for mime_type in cls.__custom_mimetypes:
            # Check if the file name ends with the suffixes, starting at the first . encountered.
            # This means that "suffix" will not match, ".suffix" will and "suffix.something.suffix" will also match
            if file_name.lower().endswith(tuple(mime_type.suffixes), file_name.find(".")):
                matches.append(mime_type)

        if len(matches) > 1:
            longest_suffix = ""
            longest_mime = None
            for match in matches:
                max_suffix = max(match.suffixes)
                if len(max_suffix) > len(longest_suffix):
                    longest_suffix = max_suffix
                    longest_mime = match
            return cast(MimeType, longest_mime)
        elif matches:
            return matches[0]

        mime = cls.__system_database.mimeTypeForFile(file_name)
        if not mime.isDefault() and mime.isValid():
            return MimeType.fromQMimeType(mime)

        raise MimeTypeNotFoundError("Could not find a valid MIME type for {0}".format(file_name)) 
Example 26
Source File: ContainerRegistry.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getMimeTypeForContainer(cls, container_type: type) -> Optional[MimeType]:
        """Retrieve the mime type corresponding to a certain container type

        :param container_type: The type of container to get the mime type for.

        :return: A MimeType object that matches the mime type of the container or None if not found.
        """

        try:
            mime_type_name = UM.Dictionary.findKey(cls.mime_type_map, container_type)
            if mime_type_name:
                return MimeTypeDatabase.getMimeType(mime_type_name)
        except ValueError:
            Logger.log("w", "Unable to find mimetype for container %s", container_type)
        return None 
Example 27
Source File: ContainerRegistry.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getContainerForMimeType(cls, mime_type):
        """Get the container type corresponding to a certain mime type.

        :param mime_type: The mime type to get the container type for.

        :return: A class object of a container type that corresponds to the specified mime type or None if not found.
        """

        return cls.mime_type_map.get(mime_type.name, None) 
Example 28
Source File: crawler.py    From spidy with GNU General Public License v3.0 5 votes vote down vote up
def get_mime_type(page):
    """
    Extracts the Content-Type header from the headers returned by page.
    """
    try:
        doc_type = str(page.headers['content-type'])
        return doc_type
    except KeyError:  # If no Content-Type was returned, return blank
        return '' 
Example 29
Source File: media.py    From gprime with GNU General Public License v2.0 5 votes vote down vote up
def get_mime_type(self):
        """
        Return the MIME type associated with the Media.

        :returns: Returns the associated MIME type
        :rtype: str
        """
        return self.mime 
Example 30
Source File: microWebSrv.py    From MicroWebSrv with MIT License 5 votes vote down vote up
def GetMimeTypeFromFilename(self, filename) :
        filename = filename.lower()
        for ext in self._mimeTypes :
            if filename.endswith(ext) :
                return self._mimeTypes[ext]
        return None

    # ---------------------------------------------------------------------------- 
Example 31
Source File: graphqlview.py    From graphql-server-core with MIT License 5 votes vote down vote up
def get_mime_type(request):
        # We use mime type here since we don't need the other
        # information provided by content_type
        if "content-type" not in request.headers:
            return None

        mime_type, _ = parse_header(request.headers["content-type"])
        return mime_type 
Example 32
Source File: gltf2_get.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def get_image_exported_mime_type(bl_image):

    if bl_image.file_format == 'JPEG':
        return 'image/jpeg'
    elif bl_image.file_format == 'BMP':
        return 'image/bmp'
    elif bl_image.file_format == 'HDR':
        return 'image/vnd.radiance'
    else:
        return 'image/png'