Python mimetypes.init() Examples

The following are 30 code examples of mimetypes.init(). 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: OPKHelper.py    From PyMenu with GNU General Public License v3.0 6 votes vote down vote up
def getFileExtensions(mime):
    if(not mimetypes.inited):
        mimetypes.init()
        initKnowMimetypes()

    types = mime.split(";")

    result = []

    for t in types:
        if(t):
            res = mimetypes.guess_all_extensions(t)
            #print("getting extensions for mime " + str(t) + " " + str(res))
            result.extend(res)

    if(len(result) == 0):
        result.append(".*")
        
    return result 
Example #2
Source File: SmeegeScrape.py    From SmeegeScrape with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def fileDir(dirInput, recursive):
    if os.path.isdir(dirInput):
        print "Scraping Files in Local Directory {0}- {1}".format('(recursively) ' if recursive else '', dirInput)
        mimetypes.init()
        fileTypes = ('*.conf', '*.cs', '*.js', '*.c', '*.cpp', '*.c++', '*.pdf', '*.docx', '*.txt', '*.csv', '*.py', '*.cpp', '*.pl', '*.log', '*.rtf', '*.css', '*.dat', '*.html', '*.php', '*.pps', '*.ppt', '*.pptx', '*.sh', '*.xml', '*.xsl')
        if recursive:
            for root, dirs, files in os.walk(dirInput):
                for fileType in fileTypes:
                    for file_name in fnmatch.filter(files, fileType):
                        file_path = os.path.join(root, file_name)
                        file_type, file_encoding = mimetypes.guess_type(file_path)
                        localFile(file_path)
        else:
            for fileType in fileTypes:
                for globFile in glob.glob(os.path.join(dirInput, fileType)):
                    file_type, file_encoding = mimetypes.guess_type(globFile)
                    localFile(globFile)
    else:
        print 'Error accessing directory: {0}'.format(dirInput) 
Example #3
Source File: test_mimetypes.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_registry_read_error(self):
        import _winreg

        class MockWinreg(object):
            def OpenKey(self, key, name):
                if key != _winreg.HKEY_CLASSES_ROOT:
                    raise WindowsError(5, "Access is denied")
                return _winreg.OpenKey(key, name)
            def __getattr__(self, name):
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #4
Source File: test_mimetypes.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_non_latin_type(self):
        import _winreg

        class MockWinreg(object):
            def __getattr__(self, name):
                if name == 'QueryValueEx':
                    return lambda subkey, label: (u'текст/простой', _winreg.REG_SZ)
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            # this used to throw an exception if registry contained non-Latin
            # characters in content types (issue #9291)
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #5
Source File: test_mimetypes.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_non_latin_extension(self):
        import _winreg

        class MockWinreg(object):
            def __getattr__(self, name):
                if name == 'EnumKey':
                    return lambda key, i: _winreg.EnumKey(key, i) + "\xa3"
                elif name == 'OpenKey':
                    return lambda key, name: _winreg.OpenKey(key, name.rstrip("\xa3"))
                elif name == 'QueryValueEx':
                    return lambda subkey, label: (u'текст/простой' , _winreg.REG_SZ)
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            # this used to throw an exception if registry contained non-Latin
            # characters in extensions (issue #9291)
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #6
Source File: local.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def distribute(self, filepath, allow_folders=True):
        self._checkpath(filepath)
        path = os.path.abspath(os.path.join(self.prefix, filepath))
        if not os.path.exists(path):
            return ("invalid", None, None)
        if os.path.isdir(path):
            if not allow_folders:
                return ("invalid", None, None)
            zipf = zipstream.ZipFile()
            for root, _, files in os.walk(path):
                for filename in files:
                    file_path = os.path.join(root, filename)
                    arcpath = os.path.relpath(file_path, path)
                    zipf.write(file_path, arcpath)
            return ("local", "application/zip", zipf.__iter__()) #the __iter__ is only present to fix a bug in web.py for py3; it only recognizes
                                                                 #iterable that possess a __next__. ZipFile.__iter__ returns an iterable in the web.py
                                                                 #sense
        elif os.path.isfile(path):
            mimetypes.init()
            mime_type = mimetypes.guess_type(path)
            return ("local", mime_type[0], open(path, 'rb')) 
Example #7
Source File: test_mimetypes.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_registry_read_error(self):
        import _winreg

        class MockWinreg(object):
            def OpenKey(self, key, name):
                if key != _winreg.HKEY_CLASSES_ROOT:
                    raise WindowsError(5, "Access is denied")
                return _winreg.OpenKey(key, name)
            def __getattr__(self, name):
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #8
Source File: test_mimetypes.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_non_latin_type(self):
        import _winreg

        class MockWinreg(object):
            def __getattr__(self, name):
                if name == 'QueryValueEx':
                    return lambda subkey, label: (u'текст/простой', _winreg.REG_SZ)
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            # this used to throw an exception if registry contained non-Latin
            # characters in content types (issue #9291)
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #9
Source File: test_mimetypes.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_non_latin_extension(self):
        import _winreg

        class MockWinreg(object):
            def __getattr__(self, name):
                if name == 'EnumKey':
                    return lambda key, i: _winreg.EnumKey(key, i) + "\xa3"
                elif name == 'OpenKey':
                    return lambda key, name: _winreg.OpenKey(key, name.rstrip("\xa3"))
                elif name == 'QueryValueEx':
                    return lambda subkey, label: (u'текст/простой' , _winreg.REG_SZ)
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            # this used to throw an exception if registry contained non-Latin
            # characters in extensions (issue #9291)
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #10
Source File: server.py    From tavern with MIT License 6 votes vote down vote up
def upload_fake_file():
    if not request.files:
        return "", 401

    if not mimetypes.inited:
        mimetypes.init()

    for key, item in request.files.items():
        if item.filename:
            filetype = ".{}".format(item.filename.split(".")[-1])
            if filetype in mimetypes.suffix_map:
                if not item.content_type:
                    return "", 400

    # Try to download each of the files downloaded to /tmp and
    # then remove them
    for key in request.files:
        file_to_save = request.files[key]
        path = os.path.join("/tmp", file_to_save.filename)
        file_to_save.save(path)

    return "", 200 
Example #11
Source File: leaflet.py    From flexx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def init(self):
        with flx.HBox():
            self.leaflet = LeafletWidget(
                flex=1,
                center=(52, 4.1),
                zoom=12,
                show_scale=lambda: self.cbs.checked,
                show_layers=lambda: self.cbl.checked,
            )
            with flx.VBox():
                self.btna = flx.Button(text='Add SeaMap')
                self.btnr = flx.Button(text='Remove SeaMap')
                self.cbs = flx.CheckBox(text='Show scale')
                self.cbl = flx.CheckBox(text='Show layers')
                self.list = flx.VBox()
                flx.Widget(flex=1)

        self.leaflet.add_layer('http://a.tile.openstreetmap.org/', 'OpenStreetMap') 
Example #12
Source File: problem_data.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def problem_init_view(request, problem):
    problem = get_object_or_404(Problem, code=problem)
    if not problem.is_editable_by(request.user):
        raise Http404()

    try:
        with problem_data_storage.open(os.path.join(problem.code, 'init.yml'), 'rb') as f:
            data = utf8text(f.read()).rstrip('\n')
    except IOError:
        raise Http404()

    return render(request, 'problem/yaml.html', {
        'raw_source': data, 'highlighted_source': highlight_code(data, 'yaml'),
        'title': _('Generated init.yml for %s') % problem.name,
        'content_title': mark_safe(escape(_('Generated init.yml for %s')) % (
            format_html('<a href="{1}">{0}</a>', problem.name,
                        reverse('problem_detail', args=[problem.code])))),
    }) 
Example #13
Source File: projects.py    From sumatra with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def load_project(path=None):
    """
    Read project from directory passed as the argument and return Project
    object. If no argument is given, the project is read from the current
    directory.
    """
    if not path:
        p = os.getcwd()
    else:
        p = os.path.abspath(path)
    while not os.path.isdir(os.path.join(p, ".smt")):
        oldp, p = p, os.path.dirname(p)
        if p == oldp:
            raise IOError("No Sumatra project exists in the current directory or above it.")
    mimetypes.init(mimetypes.knownfiles + [os.path.join(p, ".smt", "mime.types")])
    # try:
    prj = _load_project_from_json(p)
    # except Exception:
    #    prj = _load_project_from_pickle(p)
    return prj 
Example #14
Source File: test_mimetypes.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_registry_read_error(self):
        import _winreg

        class MockWinreg(object):
            def OpenKey(self, key, name):
                if key != _winreg.HKEY_CLASSES_ROOT:
                    raise WindowsError(5, "Access is denied")
                return _winreg.OpenKey(key, name)
            def __getattr__(self, name):
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #15
Source File: test_mimetypes.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_non_latin_type(self):
        import _winreg

        class MockWinreg(object):
            def __getattr__(self, name):
                if name == 'QueryValueEx':
                    return lambda subkey, label: (u'текст/простой', _winreg.REG_SZ)
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            # this used to throw an exception if registry contained non-Latin
            # characters in content types (issue #9291)
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #16
Source File: test_mimetypes.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_non_latin_extension(self):
        import _winreg

        class MockWinreg(object):
            def __getattr__(self, name):
                if name == 'EnumKey':
                    return lambda key, i: _winreg.EnumKey(key, i) + "\xa3"
                elif name == 'OpenKey':
                    return lambda key, name: _winreg.OpenKey(key, name.rstrip("\xa3"))
                elif name == 'QueryValueEx':
                    return lambda subkey, label: (u'текст/простой' , _winreg.REG_SZ)
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            # this used to throw an exception if registry contained non-Latin
            # characters in extensions (issue #9291)
            mimetypes.init()
        finally:
            mimetypes._winreg = _winreg 
Example #17
Source File: test_mimetypes.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes() 
Example #18
Source File: service.py    From aws-extender with MIT License 5 votes vote down vote up
def __init__(self, config_file=None, mimetype_files=None):
        super(Service, self).__init__(config_file)
        self.name = self.__class__.__name__
        self.working_dir = boto.config.get('Pyami', 'working_dir')
        self.sd = ServiceDef(config_file)
        self.retry_count = self.sd.getint('retry_count', 5)
        self.loop_delay = self.sd.getint('loop_delay', 30)
        self.processing_time = self.sd.getint('processing_time', 60)
        self.input_queue = self.sd.get_obj('input_queue')
        self.output_queue = self.sd.get_obj('output_queue')
        self.output_domain = self.sd.get_obj('output_domain')
        if mimetype_files:
            mimetypes.init(mimetype_files) 
Example #19
Source File: test_mimetypes.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registry_parsing(self):
        # the original, minimum contents of the MIME database in the
        # Windows registry is undocumented AFAIK.
        # Use file types that should *always* exist:
        eq = self.assertEqual
        mimetypes.init()
        db = mimetypes.MimeTypes()
        eq(db.guess_type("foo.txt"), ("text/plain", None))
        eq(db.guess_type("image.jpg"), ("image/jpeg", None))
        eq(db.guess_type("image.png"), ("image/png", None)) 
Example #20
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 #21
Source File: test_mimetypes.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_type_map_values(self):
        import _winreg

        class MockWinreg(object):
            def __getattr__(self, name):
                if name == 'QueryValueEx':
                    return lambda subkey, label: (u'text/plain', _winreg.REG_SZ)
                return getattr(_winreg, name)

        mimetypes._winreg = MockWinreg()
        try:
            mimetypes.init()
            self.assertTrue(isinstance(mimetypes.types_map.values()[0], str))
        finally:
            mimetypes._winreg = _winreg 
Example #22
Source File: test_mimetypes.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes() 
Example #23
Source File: test_static.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_usesGlobalInitFunction(self):
        """
        By default, C{mimetypes.init} is called.
        """
        # Checking mimetypes.inited doesn't always work, because
        # something, somewhere, calls mimetypes.init. Yay global
        # mutable state :)
        if getattr(inspect, "signature", None):
            signature = inspect.signature(static.loadMimeTypes)
            self.assertIs(signature.parameters["init"].default,
                          mimetypes.init)
        else:
            args, _, _, defaults = inspect.getargspec(static.loadMimeTypes)
            defaultInit = defaults[args.index("init")]
            self.assertIs(defaultInit, mimetypes.init) 
Example #24
Source File: test_mimetypes.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes() 
Example #25
Source File: file.py    From PeekabooAV with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sample):
        self.sample = sample

        if not mimetypes.inited:
            mimetypes.init()
            mimetypes.add_type('application/javascript', '.jse') 
Example #26
Source File: PostProcessor.py    From WebTrap with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _init_mimetypes(self):
        mimetypes.init()
        for missing_mime_type in self.MISSING_MIME_TYPES:
            mimetypes.add_type(missing_mime_type, self.MISSING_MIME_TYPES[missing_mime_type]) 
Example #27
Source File: multimedia_01.py    From Modern-Python-Standard-Library-Cookbook with MIT License 5 votes vote down vote up
def guess_file_type(filename):
    if not getattr(guess_file_type, 'initialised', False):
        mimetypes.init()
        guess_file_type.initialised = True
    file_type, encoding = mimetypes.guess_type(filename)
    return file_type 
Example #28
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 #29
Source File: server.py    From tavern with MIT License 5 votes vote down vote up
def upload_fake_file_and_data():
    if not request.files:
        return "", 401

    if not request.form.to_dict():
        return "", 402

    # Verify that the content type is `multipart`
    if not request.content_type.startswith("multipart/form-data"):
        return "", 403

    if not mimetypes.inited:
        mimetypes.init()

    for key, item in request.files.items():
        if item.filename:
            filetype = ".{}".format(item.filename.split(".")[-1])
            if filetype in mimetypes.suffix_map:
                if not item.content_type:
                    return "", 400

    # Try to download each of the files downloaded to /tmp
    for key in request.files:
        file_to_save = request.files[key]
        path = os.path.join("/tmp", file_to_save.filename)
        file_to_save.save(path)

    return "", 200 
Example #30
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'