summaryrefslogtreecommitdiff
path: root/Lib/mimetypes.py
diff options
context:
space:
mode:
authorAntoine Pitrou <solipsis@pitrou.net>2009-11-15 14:25:16 +0000
committerAntoine Pitrou <solipsis@pitrou.net>2009-11-15 14:25:16 +0000
commitb8108e2425546635176495dec0d70d3c87a1f309 (patch)
treebc52314e29d106ab4c243bbe8c296b43c2dd565b /Lib/mimetypes.py
parent6f1d04945b98cd66b95131833942526c85bbb867 (diff)
downloadcpython-git-b8108e2425546635176495dec0d70d3c87a1f309.tar.gz
Merged revisions 76306 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r76306 | antoine.pitrou | 2009-11-15 15:10:48 +0100 (dim., 15 nov. 2009) | 4 lines Issue #4969: The mimetypes module now reads the MIME database from the registry under Windows. Patch by Gabriel Genellina. ........
Diffstat (limited to 'Lib/mimetypes.py')
-rw-r--r--Lib/mimetypes.py48
1 files changed, 47 insertions, 1 deletions
diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py
index f0da453da0..f63a733e87 100644
--- a/Lib/mimetypes.py
+++ b/Lib/mimetypes.py
@@ -18,13 +18,19 @@ types_map -- dictionary mapping suffixes to types
Functions:
-init([files]) -- parse a list of files, default knownfiles
+init([files]) -- parse a list of files, default knownfiles (on Windows, the
+ default values are taken from the registry)
read_mime_types(file) -- parse one file, return a dictionary or None
"""
import os
+import sys
import posixpath
import urllib.parse
+try:
+ import winreg as _winreg
+except ImportError:
+ _winreg = None
__all__ = [
"guess_type","guess_extension","guess_all_extensions",
@@ -220,6 +226,44 @@ class MimeTypes:
for suff in suffixes:
self.add_type(type, '.' + suff, strict)
+ def read_windows_registry(self, strict=True):
+ """
+ Load the MIME types database from Windows registry.
+
+ If strict is true, information will be added to
+ list of standard types, else to the list of non-standard
+ types.
+ """
+
+ # Windows only
+ if not _winreg:
+ return
+
+ def enum_types(mimedb):
+ i = 0
+ while True:
+ try:
+ ctype = _winreg.EnumKey(mimedb, i)
+ except EnvironmentError:
+ break
+ else:
+ yield ctype
+ i += 1
+
+ default_encoding = sys.getdefaultencoding()
+ with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
+ r'MIME\Database\Content Type') as mimedb:
+ for ctype in enum_types(mimedb):
+ with _winreg.OpenKey(mimedb, ctype) as key:
+ try:
+ suffix, datatype = _winreg.QueryValueEx(key, 'Extension')
+ except EnvironmentError:
+ continue
+ if datatype != _winreg.REG_SZ:
+ continue
+ self.add_type(ctype, suffix, strict)
+
+
def guess_type(url, strict=True):
"""Guess the type of a file based on its URL.
@@ -299,6 +343,8 @@ def init(files=None):
inited = True # so that MimeTypes.__init__() doesn't call us again
db = MimeTypes()
if files is None:
+ if _winreg:
+ db.read_windows_registry()
files = knownfiles
for file in files:
if os.path.isfile(file):