Python mimetypes.inited() Examples

The following are 11 code examples of mimetypes.inited(). 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: 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 #3
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 #4
Source File: http_server.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def guess_mime_type(filename):
  """Guess mime type based of file extension."""
  if not mimetypes.inited:
    mimetypes.init()

  return mimetypes.guess_type(filename)[0] 
Example #5
Source File: test_static.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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 _PY3:
            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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: request.py    From tavern with MIT License 4 votes vote down vote up
def _get_file_arguments(request_args, stack):
    """Get corect arguments for anything that should be passed as a file to
    requests

    Args:
        stack (ExitStack): context stack to add file objects to so they're
            closed correctly after use

    Returns:
        dict: mapping of {"files": ...} to pass directly to requests
    """

    files_to_send = {}

    for key, filespec in request_args.get("files", {}).items():
        if not mimetypes.inited:
            mimetypes.init()

        filepath, content_type, encoding = _read_filespec(filespec)

        filename = os.path.basename(filepath)

        # a 2-tuple ('filename', fileobj)
        file_spec = [filename, stack.enter_context(open(filepath, "rb"))]

        # Try to guess as well, but don't override what the user specified
        guessed_content_type, guessed_encoding = mimetypes.guess_type(filepath)
        content_type = content_type or guessed_content_type
        encoding = encoding or guessed_encoding

        # If it doesn't have a mimetype, or can't guess it, don't
        # send the content type for the file
        if content_type:
            # a 3-tuple ('filename', fileobj, 'content_type')
            logger.debug("content_type for '%s' = '%s'", filename, content_type)
            file_spec.append(content_type)
            if encoding:
                # or a 4-tuple ('filename', fileobj, 'content_type', custom_headers)
                logger.debug("encoding for '%s' = '%s'", filename, encoding)
                # encoding is None for no encoding or the name of the
                # program used to encode (e.g. compress or gzip). The
                # encoding is suitable for use as a Content-Encoding header.
                file_spec.append({"Content-Encoding": encoding})

        files_to_send[key] = tuple(file_spec)

    if files_to_send:
        return {"files": files_to_send}
    else:
        return {}