diff -r d6aa3fa646e2 Lib/mimetypes.py --- a/Lib/mimetypes.py Fri Feb 21 18:30:53 2014 -0500 +++ b/Lib/mimetypes.py Sat Mar 01 10:07:39 2014 -0700 @@ -68,6 +68,7 @@ self.suffix_map = suffix_map.copy() self.types_map = ({}, {}) # dict for (non-strict, strict) self.types_map_inv = ({}, {}) + self.canonical_map = canonical_map.copy() for (ext, type) in types_map.items(): self.add_type(type, ext, True) for (ext, type) in common_types.items(): @@ -186,6 +187,9 @@ Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ + type = type.lower() + if type in self.canonical_map: + return self.canonical_map[type] extensions = self.guess_all_extensions(type, strict) if not extensions: return None @@ -339,7 +343,7 @@ def init(files=None): - global suffix_map, types_map, encodings_map, common_types + global suffix_map, types_map, encodings_map, common_types, canonical_map global inited, _db inited = True # so that MimeTypes.__init__() doesn't call us again db = MimeTypes() @@ -354,6 +358,7 @@ suffix_map = db.suffix_map types_map = db.types_map[True] common_types = db.types_map[False] + canonical_map = db.canonical_map # Make the DB a global variable now that it is fully initialized _db = db @@ -374,6 +379,7 @@ global encodings_map global types_map global common_types + global canonical_map suffix_map = { '.svgz': '.svg.gz', @@ -542,6 +548,13 @@ '.xul' : 'text/xul' } + # Certain types have well-known extensions. These will be returned + # unconditionally from guess_extension. + + canonical_map = { + 'text/plain': '.txt', + } + _default_mime_types() diff -r d6aa3fa646e2 Lib/test/test_mimetypes.py --- a/Lib/test/test_mimetypes.py Fri Feb 21 18:30:53 2014 -0500 +++ b/Lib/test/test_mimetypes.py Sat Mar 01 10:07:39 2014 -0700 @@ -3,6 +3,7 @@ import mimetypes import sys import unittest +import unittest.mock as mock from test import support @@ -77,6 +78,12 @@ strict=True) self.assertEqual(exts, ['.g3', '.g\xb3']) + def test_canonical_extensions(self): + eq = self.assertEqual + with mock.patch.dict(self.db.canonical_map, {'foo/bar': '.bar'}): + eq(self.db.guess_extension('foo/bar', strict=True), '.bar') + eq(self.db.guess_extension('foo/bar', strict=False), '.bar') + @unittest.skipUnless(sys.platform.startswith("win"), "Windows only") class Win32MimeTypesTestCase(unittest.TestCase):