Python mimetypes.types_map() Examples

The following are 17 code examples of mimetypes.types_map(). 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. You may also want to check out all available functions/classes of the module mimetypes , or try the search function .
Example #1
Source File: constants.py    From sentinelhub-py with MIT License 6 votes vote down vote up
def get_string(self):
        """ Get file format as string

        :return: String describing the file format
        :rtype: str
        """
        if self is MimeType.TAR:
            return 'application/x-tar'
        if self is MimeType.JSON:
            return 'application/json'
        if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]:
            return 'image/{}'.format(self.value)
        if self is MimeType.JP2:
            return 'image/jpeg2000'
        if self is MimeType.RAW:
            return self.value
        return mimetypes.types_map['.' + self.value] 
Example #2
Source File: guess_filetype.py    From nzb-subliminal with GNU General Public License v3.0 6 votes vote down vote up
def process(self, mtree, options=None):
        """guess the file type now (will be useful later)
        """
        filetype, other = self.guess_filetype(mtree, options)

        mtree.guess.set('type', filetype, confidence=1.0)
        log_found_guess(mtree.guess)

        filetype_info = Guess(other, confidence=1.0)
        # guess the mimetype of the filename
        # TODO: handle other mimetypes not found on the default type_maps
        # mimetypes.types_map['.srt']='text/subtitle'
        mime, _ = mimetypes.guess_type(mtree.string, strict=False)
        if mime is not None:
            filetype_info.update({'mimetype': mime}, confidence=1.0)

        node_ext = mtree.node_at((-1,))
        found_guess(node_ext, filetype_info)

        if mtree.guess.get('type') in [None, 'unknown']:
            if options.get('name_only'):
                mtree.guess.set('type', 'movie', confidence=0.6)
            else:
                raise TransformerException(__name__, 'Unknown file type') 
Example #3
Source File: util.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def loadMimeTypes(mimetype_locations=['/etc/mime.types']):
    """
    Multiple file locations containing mime-types can be passed as a list.
    The files will be sourced in that order, overriding mime-types from the
    files sourced beforehand, but only if a new entry explicitly overrides
    the current entry.
    """
    import mimetypes
    # Grab Python's built-in mimetypes dictionary.
    contentTypes = mimetypes.types_map  # @UndefinedVariable
    # Update Python's semi-erroneous dictionary with a few of the
    # usual suspects.
    contentTypes.update(
        {
            '.conf': 'text/plain',
            '.diff': 'text/plain',
            '.exe': 'application/x-executable',
            '.flac': 'audio/x-flac',
            '.java': 'text/plain',
            '.ogg': 'application/ogg',
            '.oz': 'text/x-oz',
            '.swf': 'application/x-shockwave-flash',
            '.tgz': 'application/x-gtar',
            '.wml': 'text/vnd.wap.wml',
            '.xul': 'application/vnd.mozilla.xul+xml',
            '.py': 'text/plain',
            '.patch': 'text/plain',
        }
    )
    # Users can override these mime-types by loading them out configuration
    # files (this defaults to ['/etc/mime.types']).
    for location in mimetype_locations:
        if os.path.exists(location):
            contentTypes.update(mimetypes.read_mime_types(location))

    return contentTypes 
Example #4
Source File: static.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def _setup_mimetypes():
    """Pre-initialize global mimetype map."""
    if not mimetypes.inited:
        mimetypes.init()
    mimetypes.types_map['.dwg'] = 'image/x-dwg'
    mimetypes.types_map['.ico'] = 'image/x-icon'
    mimetypes.types_map['.bz2'] = 'application/x-bzip2'
    mimetypes.types_map['.gz'] = 'application/x-gzip' 
Example #5
Source File: youtube2peertube.py    From YouTube2PeerTube with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_file(file_path):
    mimetypes.init()
    return (path.basename(file_path), open(path.abspath(file_path), 'rb'),
            mimetypes.types_map[path.splitext(file_path)[1]]) 
Example #6
Source File: static.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def loadMimeTypes(mimetype_locations=['/etc/mime.types']):
    """
    Multiple file locations containing mime-types can be passed as a list.
    The files will be sourced in that order, overriding mime-types from the
    files sourced beforehand, but only if a new entry explicitly overrides
    the current entry.
    """
    import mimetypes
    # Grab Python's built-in mimetypes dictionary.
    contentTypes = mimetypes.types_map
    # Update Python's semi-erroneous dictionary with a few of the
    # usual suspects.
    contentTypes.update(
        {
            '.conf':  'text/plain',
            '.diff':  'text/plain',
            '.exe':   'application/x-executable',
            '.flac':  'audio/x-flac',
            '.java':  'text/plain',
            '.ogg':   'application/ogg',
            '.oz':    'text/x-oz',
            '.swf':   'application/x-shockwave-flash',
            '.tgz':   'application/x-gtar',
            '.wml':   'text/vnd.wap.wml',
            '.xul':   'application/vnd.mozilla.xul+xml',
            '.py':    'text/plain',
            '.patch': 'text/plain',
        }
    )
    # Users can override these mime-types by loading them out configuration
    # files (this defaults to ['/etc/mime.types']).
    for location in mimetype_locations:
        if os.path.exists(location):
            more = mimetypes.read_mime_types(location)
            if more is not None:
                contentTypes.update(more)
            
    return contentTypes 
Example #7
Source File: static.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def loadMimeTypes(mimetype_locations=['/etc/mime.types']):
    """
    Multiple file locations containing mime-types can be passed as a list.
    The files will be sourced in that order, overriding mime-types from the
    files sourced beforehand, but only if a new entry explicitly overrides
    the current entry.
    """
    import mimetypes
    # Grab Python's built-in mimetypes dictionary.
    contentTypes = mimetypes.types_map
    # Update Python's semi-erroneous dictionary with a few of the
    # usual suspects.
    contentTypes.update(
        {
            '.conf':  'text/plain',
            '.diff':  'text/plain',
            '.exe':   'application/x-executable',
            '.flac':  'audio/x-flac',
            '.java':  'text/plain',
            '.ogg':   'application/ogg',
            '.oz':    'text/x-oz',
            '.swf':   'application/x-shockwave-flash',
            '.tgz':   'application/x-gtar',
            '.wml':   'text/vnd.wap.wml',
            '.xul':   'application/vnd.mozilla.xul+xml',
            '.py':    'text/plain',
            '.patch': 'text/plain',
        }
    )
    # Users can override these mime-types by loading them out configuration
    # files (this defaults to ['/etc/mime.types']).
    for location in mimetype_locations:
        if os.path.exists(location):
            more = mimetypes.read_mime_types(location)
            if more is not None:
                contentTypes.update(more)

    return contentTypes 
Example #8
Source File: __init__.py    From restapi with GNU General Public License v2.0 5 votes vote down vote up
def editItemInfo(self, itemInfo, thumbnailFile=None):
        """Edits the itemInfo for service.
        
        Args:
            itemInfo: JSON itemInfo objet representing metadata.
            thumbnailFile: Path to optional thumbnail image, defaults to None.
        """

        query_url = self.url + '/iteminfo/edit'
        if thumbnailFile and os.path.exists(thumbnailFile):
            # use mimetypes to guess "content_type"
            import mimetypes
            known = mimetypes.types_map
            common = mimetypes.common_types
            ext = os.path.splitext(thumbnailFile)[-1].lower()
            content_type = 'image/jpg'
            if ext in known:
                content_type = known[ext]
            elif ext in common:
                content_type = common[ext]

            # make multi-part encoded file
            files = {'thumbnail': (os.path.basename(thumbnailFile), open(thumbnailFile, 'rb'), content_type)}
        else:
            files = ''

        params = {'serviceItemInfo': json.dumps(itemInfo) if isinstance(itemInfo, dict) else itemInfo,
                  'token': self.token.token if isinstance(self.token, Token) else self.token,
                  'f': 'json'}

        return requests.post(query_url, params, files=files, verify=False).json() 
Example #9
Source File: leaflet.py    From flexx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _embed_css_resources(css, types=('.png',)):
    """ Replace urls in css with data urls
    """
    type_str = '|'.join('\%s' % t for t in types)
    rx = re.compile('(url\s*\(\s*(.*(%s))\s*\))' % type_str)
    found = rx.findall(css)
    for match, item, ext in found:
        data = base64.b64encode(_get_data(item)).decode()
        mime = mimetypes.types_map[ext]
        repl = 'url(data:%s;base64,%s)' % (mime, data)
        css = css.replace(match, repl)
    return css 
Example #10
Source File: document.py    From pympress with GNU General Public License v2.0 5 votes vote down vote up
def get_extension(mime_type):
    """ Returns a valid filename extension (recognized by python) for a given mime type.

    Args:
        mime_type (`str`): The mime type for which to find an extension

    Returns:
        `str`: A file extension used for the given mimetype
    """
    if not mimetypes.inited:
        mimetypes.init()
    for ext in mimetypes.types_map:
        if mimetypes.types_map[ext] == mime_type:
            return ext 
Example #11
Source File: static.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def loadMimeTypes(mimetype_locations=['/etc/mime.types']):
    """
    Multiple file locations containing mime-types can be passed as a list.
    The files will be sourced in that order, overriding mime-types from the
    files sourced beforehand, but only if a new entry explicitly overrides
    the current entry.
    """
    import mimetypes
    # Grab Python's built-in mimetypes dictionary.
    contentTypes = mimetypes.types_map  # @UndefinedVariable
    # Update Python's semi-erroneous dictionary with a few of the
    # usual suspects.
    contentTypes.update(
        {
            '.conf': 'text/plain',
            '.diff': 'text/plain',
            '.exe': 'application/x-executable',
            '.flac': 'audio/x-flac',
            '.java': 'text/plain',
            '.ogg': 'application/ogg',
            '.oz': 'text/x-oz',
            '.swf': 'application/x-shockwave-flash',
            '.tgz': 'application/x-gtar',
            '.wml': 'text/vnd.wap.wml',
            '.xul': 'application/vnd.mozilla.xul+xml',
            '.py': 'text/plain',
            '.patch': 'text/plain',
        }
    )
    # Users can override these mime-types by loading them out configuration
    # files (this defaults to ['/etc/mime.types']).
    for location in mimetype_locations:
        if os.path.exists(location):
            contentTypes.update(mimetypes.read_mime_types(location))

    return contentTypes 
Example #12
Source File: static.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _setup_mimetypes():
    """Pre-initialize global mimetype map."""
    if not mimetypes.inited:
        mimetypes.init()
    mimetypes.types_map['.dwg'] = 'image/x-dwg'
    mimetypes.types_map['.ico'] = 'image/x-icon'
    mimetypes.types_map['.bz2'] = 'application/x-bzip2'
    mimetypes.types_map['.gz'] = 'application/x-gzip' 
Example #13
Source File: static.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def loadMimeTypes(mimetype_locations=None, init=mimetypes.init):
    """
    Produces a mapping of extensions (with leading dot) to MIME types.

    It does this by calling the C{init} function of the L{mimetypes} module.
    This will have the side effect of modifying the global MIME types cache
    in that module.

    Multiple file locations containing mime-types can be passed as a list.
    The files will be sourced in that order, overriding mime-types from the
    files sourced beforehand, but only if a new entry explicitly overrides
    the current entry.

    @param mimetype_locations: Optional. List of paths to C{mime.types} style
        files that should be used.
    @type mimetype_locations: iterable of paths or L{None}
    @param init: The init function to call. Defaults to the global C{init}
        function of the C{mimetypes} module. For internal use (testing) only.
    @type init: callable
    """
    init(mimetype_locations)
    mimetypes.types_map.update(
        {
            '.conf':  'text/plain',
            '.diff':  'text/plain',
            '.flac':  'audio/x-flac',
            '.java':  'text/plain',
            '.oz':    'text/x-oz',
            '.swf':   'application/x-shockwave-flash',
            '.wml':   'text/vnd.wap.wml',
            '.xul':   'application/vnd.mozilla.xul+xml',
            '.patch': 'text/plain'
        }
    )
    return mimetypes.types_map 
Example #14
Source File: static.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def loadMimeTypes(mimetype_locations=None, init=mimetypes.init):
    """
    Produces a mapping of extensions (with leading dot) to MIME types.

    It does this by calling the C{init} function of the L{mimetypes} module.
    This will have the side effect of modifying the global MIME types cache
    in that module.

    Multiple file locations containing mime-types can be passed as a list.
    The files will be sourced in that order, overriding mime-types from the
    files sourced beforehand, but only if a new entry explicitly overrides
    the current entry.

    @param mimetype_locations: Optional. List of paths to C{mime.types} style
        files that should be used.
    @type mimetype_locations: iterable of paths or L{None}
    @param init: The init function to call. Defaults to the global C{init}
        function of the C{mimetypes} module. For internal use (testing) only.
    @type init: callable
    """
    init(mimetype_locations)
    mimetypes.types_map.update(
        {
            '.conf':  'text/plain',
            '.diff':  'text/plain',
            '.flac':  'audio/x-flac',
            '.java':  'text/plain',
            '.oz':    'text/x-oz',
            '.swf':   'application/x-shockwave-flash',
            '.wml':   'text/vnd.wap.wml',
            '.xul':   'application/vnd.mozilla.xul+xml',
            '.patch': 'text/plain'
        }
    )
    return mimetypes.types_map 
Example #15
Source File: base.py    From Archivist with GNU General Public License v3.0 5 votes vote down vote up
def _mimetype(self):
        _, extension = path.splitext(self.filename)
        if extension == '':
            extension = '.txt'
        mimetypes.init()
        try:
            return mimetypes.types_map[extension]
        except KeyError:
            return 'plain/text' 
Example #16
Source File: manifest.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _register_mimetypes(self, filenames):
        """
        Make sure that the mime type for all file extensions is registered
        """
        for fn in filenames:
            ext = os.path.splitext(fn)[-1]
            if not ext:
                continue
            mime = mimetypes.types_map[ext]
            fe = FileExtension(ext[1:], mime)
            self.Default.append(fe) 
Example #17
Source File: manifest.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def extensions(self):
        """
        Map content types to file extensions
        Skip parts without extensions
        """
        exts = set([os.path.splitext(part.PartName)[-1] for part in self.Override])
        return [(ext[1:], mimetypes.types_map[ext]) for ext in sorted(exts) if ext]