Python mimetypes 模块,types_map() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用mimetypes.types_map()

项目:jumpscale_portal    作者:jumpscale7    | 项目源码 | 文件源码
def __mimetype(self, path):
        """Detect mimetype of file"""
        mime = mimetypes.guess_type(path)[0] or 'unknown'
        ext = path[path.rfind('.') + 1:]

        if mime == 'unknown' and ('.' + ext) in mimetypes.types_map:
            mime = mimetypes.types_map['.' + ext]

        if mime == 'text/plain' and ext == 'pl':
            mime = self._mimeType[ext]

        if mime == 'application/vnd.ms-office' and ext == 'doc':
            mime = self._mimeType[ext]

        if mime == 'unknown':
            if os.path.basename(path) in ['README', 'ChangeLog']:
                mime = 'text/plain'
            else:
                if ext in self._mimeType:
                    mime = self._mimeType[ext]

        # self.__debug('mime ' + os.path.basename(path), ext + ' ' + mime)
        return mime
项目:tk-multi-publish2    作者:shotgunsoftware    | 项目源码 | 文件源码
def _build_image_extensions_list():

    image_file_types = ["Photoshop Image", "Rendered Image", "Texture Image"]
    image_extensions = set()

    for image_file_type in image_file_types:
        image_extensions.update(COMMON_FILE_INFO[image_file_type]["extensions"])

    # get all the image mime type image extensions as well
    mimetypes.init()
    types_map = mimetypes.types_map
    for (ext, mimetype) in types_map.iteritems():
        if mimetype.startswith("image/"):
            image_extensions.add(ext.lstrip("."))

    return list(image_extensions)
项目:mongodb_backup_script    作者:hxt168    | 项目源码 | 文件源码
def get_content_type_by_filename(file_name):
    mime_type = ""
    mime_map = {}
    mime_map["js"] = "application/javascript"
    mime_map["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    mime_map["xltx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"
    mime_map["potx"] = "application/vnd.openxmlformats-officedocument.presentationml.template"
    mime_map["ppsx"] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
    mime_map["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    mime_map["sldx"] = "application/vnd.openxmlformats-officedocument.presentationml.slide"
    mime_map["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    mime_map["dotx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
    mime_map["xlam"] = "application/vnd.ms-excel.addin.macroEnabled.12"
    mime_map["xlsb"] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12"
    mime_map["apk"] = "application/vnd.android.package-archive"
    try:
        suffix = ""
        name = os.path.basename(file_name)
        suffix = name.split('.')[-1]
        if suffix in mime_map.keys():
            mime_type = mime_map[suffix] 
        else:
            import mimetypes
            mimetypes.init()
            mime_type = mimetypes.types_map["." + suffix]
    except Exception:
        mime_type = 'application/octet-stream'
    if not mime_type:
        mime_type = 'application/octet-stream'
    return mime_type
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:badge    作者:SavandBros    | 项目源码 | 文件源码
def service_badge(request, service, action, package, extension):
    gc.collect()

    if extension not in settings.ALLOWED_EXTENSIONS:
        request.setResponseCode(401)
        return "{} is not a valid extension.".format(extension)

    service_reg = service_registry.services.get(service, None)

    if not service_reg:
        request.setResponseCode(401)
        return "{} is not a valid service.".format(service)

    if action not in service_reg['actions']['all']:
        request.setResponseCode(401)
        return "{} is not a valid action.".format(action)

    service_class = service_reg['class']
    service_class = service_class(package, format=extension, extra_context=request.args)
    """:type service_class: service.base.ServiceBase"""
    service_class.pull_package_data()

    if service_class.package_pulling_failed:
        request.setResponseCode(404)
        return "Couldn't pull data from {} for package {}".format(service, package)

    ext = mimetypes.types_map[".{0}".format(extension)]
    request.headers.update({'content-type': ext})

    getattr(service_class, service_reg['actions']['all'][action])()
    img = service_class.draw_badge()

    return img
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:devcenter-open-project-migration    作者:naver    | 项目源码 | 文件源码
def read_downloads(self):
        downloads_path = os.path.join(self.project_path, DOWNLOADS_DIR)
        json_path = os.path.join(downloads_path, 'json', '*.json')
        raw_path = os.path.join(downloads_path, 'raw')

        downloads = dict()

        for file_path in glob.glob(json_path):
            download_id = int(get_fn(file_path, 0))
            downloads[download_id] = dict()

            with open(file_path) as json_text:
                downloads[download_id]['json'] = json.loads(json_text.read())

        for download_id in os.listdir(raw_path):
            downloads[int(download_id)]['raw'] = list()

            for file_path in glob.glob(os.path.join(raw_path, str(download_id),
                                                    '*.*')):
                file_name = get_fn(file_path)
                ext = get_fn(file_path, 1)

                try:
                    content_type = mimetypes.types_map[ext]
                except KeyError:
                    content_type = 'multipart/form-data'

                with open(file_path, 'rb') as raw_file:
                    downloads[int(download_id)]['raw'].append(dict(
                        name=file_name,
                        raw=raw_file.read(),
                        content_type=content_type
                    ))

        return collections.OrderedDict(sorted(downloads.items()))
项目:mWorkerService    作者:smices    | 项目源码 | 文件源码
def guess_content_type_by_file_name(file_name):
    """
    Get file type by filename.

    :type file_name: string
    :param file_name: None
    =======================
    :return:
        **Type Value**
    """
    mime_map = dict()
    mime_map["js"] = "application/javascript"
    mime_map["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    mime_map["xltx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"
    mime_map["potx"] = "application/vnd.openxmlformats-officedocument.presentationml.template"
    mime_map["ppsx"] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
    mime_map["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    mime_map["sldx"] = "application/vnd.openxmlformats-officedocument.presentationml.slide"
    mime_map["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    mime_map["dotx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
    mime_map["xlam"] = "application/vnd.ms-excel.addin.macroEnabled.12"
    mime_map["xlsb"] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12"
    try:
        name = os.path.basename(file_name)
        suffix = name.split('.')[-1]
        if suffix in mime_map.keys():
            mime_type = mime_map[suffix]
        else:
            import mimetypes

            mimetypes.init()
            mime_type = mimetypes.types_map["." + suffix]
    except:
        mime_type = 'application/octet-stream'
    if not mime_type:
        mime_type = 'application/octet-stream'
    return mime_type
项目:mWorkerService    作者:smices    | 项目源码 | 文件源码
def guess_content_type_by_file_name(file_name):
    """
    Get file type by filename.

    :type file_name: string
    :param file_name: None
    =======================
    :return:
        **Type Value**
    """
    mime_map = dict()
    mime_map["js"] = "application/javascript"
    mime_map["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    mime_map["xltx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"
    mime_map["potx"] = "application/vnd.openxmlformats-officedocument.presentationml.template"
    mime_map["ppsx"] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
    mime_map["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    mime_map["sldx"] = "application/vnd.openxmlformats-officedocument.presentationml.slide"
    mime_map["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    mime_map["dotx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
    mime_map["xlam"] = "application/vnd.ms-excel.addin.macroEnabled.12"
    mime_map["xlsb"] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12"
    try:
        name = os.path.basename(file_name)
        suffix = name.split('.')[-1]
        if suffix in mime_map.keys():
            mime_type = mime_map[suffix]
        else:
            import mimetypes

            mimetypes.init()
            mime_type = mimetypes.types_map["." + suffix]
    except:
        mime_type = 'application/octet-stream'
    if not mime_type:
        mime_type = 'application/octet-stream'
    return mime_type
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def extensions(self):
        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)]
项目:pyterrier    作者:dfurtado    | 项目源码 | 文件源码
def get_mime_type(self, path: str):
        """
        Returns the mime type base on the extension of the file that the
        client is requesting.

        path: The relative path to the static file. By default it will
        search in the static folder in the application root.
        """

        match = self._static_regex.search(path)

        if match is not None and match.group('ext') is not None:
            return mimetypes.types_map[match.group('ext')]
项目:website    作者:hackerspace-ntnu    | 项目源码 | 文件源码
def get_image_format(extension):
    mimetypes.init()
    return mimetypes.types_map[extension.lower()]
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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
项目:open-mic    作者:cosmir    | 项目源码 | 文件源码
def annotation_submit():
    """
    To POST data to this endpoint:

    $ curl -H "Content-type: application/json" \
        -X POST localhost:8080/api/v0.1/annotation/submit \
        -d '{"message":"Hello Data"}'
    """
    if request.headers['Content-Type'] == 'application/json':
        app.logger.info("Received Annotation:\n{}"
                        .format(json.dumps(request.json, indent=2)))
        # Do a thing with the annotation
        # Return some progress stats?
        data = json.dumps(dict(message='Success!'))
        status = 200

        db = pybackend.database.Database(
            project=app.config['cloud']['project'],
            **app.config['cloud']['database'])
        gid = str(pybackend.utils.uuid(json.dumps(request.json)))
        uri = pybackend.urilib.join('annotation', gid)
        record = pybackend.models.AnnotationResponse(
            created=str(datetime.datetime.now()),
            response=request.json,
            user_id='anonymous')
        db.put(uri, record.flatten())
    else:
        status = 400
        data = json.dumps(dict(message='Invalid Content-Type; '
                                       'only accepts application/json'))

    resp = Response(
        data, status=status, mimetype=mimetypes.types_map[".json"])
    resp.headers['Link'] = SOURCE
    return resp
项目:ShareFile    作者:umahmood    | 项目源码 | 文件源码
def run(self):
        _, ext = path.splitext(self.filename)

        try:
            mime_type = types_map[ext]
        except KeyError:
            mime_type = "application/octet-stream"

        with open(self.filepath, 'rb') as f:
            data = f.read()

        headers = {
            "Accept"            : "*/*",
            "Accept-Encoding"   : "gzip,deflate",
            "Accept-Language"   : "en-US,en;q=0.8",
            "Connection"        : "keep-alive",
            "Content-Length"    : len(data),
            "Content-Type"      : mime_type,
            "Host"              : "transfer.sh",
            "Origin"            : "https://transfer.sh",
            "Referer"           : "https://transfer.sh/",
            "User-Agent"        : "Mozilla/5.0",
            "X_FILENAME"        : self.filename
        }

        url = "https://transfer.sh/" + self.filename

        req = request.Request(url, data=data, headers=headers, method="PUT")

        try:
            show_status_message("ShareFile: uploading file...")
            with request.urlopen(req, timeout=10) as resp:
                if resp.status == 200:
                    body       = resp.read()
                    share_link = body.decode('utf-8').strip('\n')
                    msg        = template.format(share_link, "")
                else:
                    msg = template.format("Could not upload file",
                                          str(resp.status) + " " + resp.reason)
                clear_status_message()
                show_alert(msg)
        except URLError as e:
            msg = template.format(e.reason, "")
            show_alert(msg)