Python mimetypes.MimeTypes() Examples

The following are 30 code examples of mimetypes.MimeTypes(). 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: flask_gopher.py    From flask-gopher with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 local_directory,
                 view_name,
                 url_token='filename',
                 show_timestamp=False,
                 width=70):
        """
        Args:
            local_directory: The local file system path that will be served.
            view_name: The name of the app view that maps to the directory.
            url_token: The path will be inserted into this token in the URL.
            show_timestamp: Include the last accessed timestamp for each file.
            width: The page width to use when formatting timestamp strings.
        """
        self.local_directory = local_directory
        self.view_name = view_name
        self.url_token = url_token
        self.show_timestamp = show_timestamp
        self.width = width

        #  Custom file extensions can be added via self.mimetypes.add_type()
        self.mimetypes = mimetypes.MimeTypes() 
Example #2
Source File: server.py    From MapTilesDownloader with MIT License 6 votes vote down vote up
def do_GET(self):


		parts = urlparse(self.path)
		path = parts.path.strip('/')
		if path == "":
			path = "index.htm"

		file = os.path.join("./UI/", path)
		mime = mimetypes.MimeTypes().guess_type(file)[0] 

		self.send_response(200)
		# self.send_header("Access-Control-Allow-Origin", "*")
		self.send_header("Content-Type", mime)
		self.end_headers()
		
		with open(file, "rb") as f:
			self.wfile.write(f.read()) 
Example #3
Source File: models.py    From wagtailvideos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def video_tag(self, attrs=None):
        if attrs is None:
            attrs = {}
        else:
            attrs = attrs.copy()
        if self.thumbnail:
            attrs['poster'] = self.thumbnail.url

        transcodes = self.transcodes.exclude(processing=True).filter(error_message__exact='')
        sources = []
        for transcode in transcodes:
            sources.append("<source src='{0}' type='video/{1}' >".format(transcode.url, transcode.media_format.name))

        mime = mimetypes.MimeTypes()
        sources.append("<source src='{0}' type='{1}'>"
                       .format(self.url, mime.guess_type(self.url)[0]))

        sources.append("<p>Sorry, your browser doesn't support playback for this video</p>")
        return mark_safe(
            "<video {0}>\n{1}\n</video>".format(flatatt(attrs), "\n".join(sources))) 
Example #4
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 #5
Source File: test_mimetypes.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #6
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 #7
Source File: __init__.py    From jx-sqlite with Mozilla Public License 2.0 5 votes vote down vote up
def mime_type(self):
        if not self._mime_type:
            if self.abspath.endswith(".js"):
                self._mime_type = "application/javascript"
            elif self.abspath.endswith(".css"):
                self._mime_type = "text/css"
            elif self.abspath.endswith(".json"):
                self._mime_type = mimetype.JSON
            else:
                mime = MimeTypes()
                self._mime_type, _ = mime.guess_type(self.abspath)
                if not self._mime_type:
                    self._mime_type = "application/binary"
        return self._mime_type 
Example #8
Source File: upload.py    From telegraph with MIT License 5 votes vote down vote up
def open_files(self):
        self.close_files()

        files = []

        for x, file_or_name in enumerate(self.paths):
            name = ''
            if isinstance(file_or_name, tuple) and len(file_or_name) >= 2:
                name = file_or_name[1]
                file_or_name = file_or_name[0]

            if hasattr(file_or_name, 'read'):
                f = file_or_name

                if hasattr(f, 'name'):
                    filename = f.name
                else:
                    filename = name
            else:
                filename = file_or_name
                f = open(filename, 'rb')
                self.opened_files.append(f)

            mimetype = mimetypes.MimeTypes().guess_type(filename)[0]

            files.append(
                (self.key_format.format(x), ('file{}'.format(x), f, mimetype))
            )

        return files 
Example #9
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):
        self.db = mimetypes.MimeTypes() 
Example #10
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 test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3']) 
Example #11
Source File: test_mimetypes.py    From CTFCrackTools 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 #12
Source File: test_mimetypes.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #13
Source File: test_mimetypes.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #14
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 #15
Source File: test_mimetypes.py    From android_universal with MIT License 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #16
Source File: test_mimetypes.py    From android_universal with MIT License 5 votes vote down vote up
def test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3']) 
Example #17
Source File: test_mimetypes.py    From android_universal with MIT License 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: test_mimetypes.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #19
Source File: test_mimetypes.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3']) 
Example #20
Source File: test_utils.py    From peony-twitter with MIT License 5 votes vote down vote up
def builtin_mimetypes(func):

    @wraps(func)
    async def decorated(*args, **kwargs):
        with patch.object(utils, 'magic') as magic:
            magic.__bool__.return_value = False
            with patch.object(utils, 'mime') as mime:
                mime.guess_type.side_effect = mimetypes.MimeTypes().guess_type

                await func(*args, **kwargs)

    return decorated 
Example #21
Source File: test_mimetypes.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #22
Source File: test_mimetypes.py    From ironpython2 with Apache License 2.0 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 #23
Source File: test_mimetypes.py    From BinderFilter with MIT License 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #24
Source File: test_mimetypes.py    From BinderFilter with MIT License 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: test_mimetypes.py    From oss-ftp with MIT License 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #26
Source File: test_mimetypes.py    From oss-ftp with MIT 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 #27
Source File: static.py    From vlcp with Apache License 2.0 5 votes vote down vote up
def __init__(self, server):
        Module.__init__(self, server)
        self.dispatcher = Dispatcher(self.scheduler)
        self.mimetypedatabase = mimetypes.MimeTypes(self.mimetypes)
        self._cache = {}
        self.apiroutine = RoutineContainer(self.scheduler)
        self.lastcleartime = 0
        def start(asyncStart = False):
            self._createHandlers(self)
        def close():
            self.dispatcher.close()
        self.apiroutine.start = start
        self.apiroutine.close = close
        self.routines.append(self.apiroutine)
        self.createAPI(api(self.updateconfig)) 
Example #28
Source File: rocketchat.py    From rocketchat_API with MIT License 5 votes vote down vote up
def assets_set_asset(self, asset_name, file, **kwargs):
        """Set an asset image by name."""
        content_type = mimetypes.MimeTypes().guess_type(file)
        files = {
            asset_name: (file, open(file, 'rb'), content_type[0], {'Expires': '0'}),
        }
        return self.__call_api_post('assets.setAsset', kwargs=kwargs, use_json=False, files=files) 
Example #29
Source File: test_mimetypes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.db = mimetypes.MimeTypes() 
Example #30
Source File: test_mimetypes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3'])