[Checkins] SVN: Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/ Checkpoint: Make MIMEType simply a subclass of unicode, remove lookup function as it's not needed anymore, as MIMEType class automatically caches its objects now. Remove IConvienienceAPI as it doesn't really make sense now. More to do.

Dan Korostelev nadako at gmail.com
Tue Sep 8 13:06:04 EDT 2009


Log message for revision 103651:
  Checkpoint: Make MIMEType simply a subclass of unicode, remove lookup function as it's not needed anymore, as MIMEType class automatically caches its objects now. Remove IConvienienceAPI as it doesn't really make sense now. More to do.

Changed:
  U   Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/README.txt
  U   Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/__init__.py
  U   Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/interfaces.py
  U   Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/magic.py
  U   Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/mimetype.py
  U   Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/utility.py

-=-
Modified: Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/README.txt
===================================================================
--- Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/README.txt	2009-09-08 16:41:00 UTC (rev 103650)
+++ Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/README.txt	2009-09-08 17:06:03 UTC (rev 103651)
@@ -195,44 +195,11 @@
 Convenience API
 ---------------
 
-The root module, ``z3c.sharedmimeinfo`` provides a convenience API for easy using
-MIME types detection and lookup. It provides a IConvenienceAPI interface::
+The root module, ``z3c.sharedmimeinfo`` provides a convenience getType function
+for easy using MIME type detection mechanism.
 
   >>> import z3c.sharedmimeinfo
-  >>> from z3c.sharedmimeinfo.interfaces import IConvenienceAPI
-  >>> IConvenienceAPI.providedBy(z3c.sharedmimeinfo)
-  True
-  
-This interface defines two functions::
 
-  >>> sorted(IConvenienceAPI)
-  ['getType', 'lookup']
-
-The lookup function is used for getting IMIMEType objects by their media and
-subtype names. You can specify media and subtype as two arguments or as one,
-first argument in the "media/subtype" form.
-
-Here's how to use it with single argument::
-
-  >>> mt = z3c.sharedmimeinfo.lookup('text/plain')
-  >>> mt
-  <_MIMEType text/plain>
-  
-  >>> IMIMEType.providedBy(mt)
-  True
-
-Here's how to use passing separate media and subtype arguments::
-
-  >>> z3c.sharedmimeinfo.lookup('image', 'png')
-  <_MIMEType image/png>
-
-Note, that the IMIMETypes objects are singletons (one object per mime type), so
-if you youse lookup function with same mime type once again, you'll get the same
-object::
-
-  >>> z3c.sharedmimeinfo.lookup('text/plain') is mt
-  True
-
 The ``getType`` function is just a wrapper for the ``getType`` function of
 global mimetype utility, so it works like described above::
 
@@ -254,36 +221,32 @@
 
   >>> del fpng, funknownbinary
 
-MIME type object comparsion
----------------------------
+MIME type objects
+-----------------
 
-It's own useful to compare a mime type to some string if we need to check if
-some file is of specific type, the IMIMEType objects should be comparable to
-strings::
+MIMEType class are actually an extended str that adds additional info about
+the mime type, like its title, media and subtype.
 
-  >>> mt = z3c.sharedmimeinfo.lookup('image/png')
-  >>> mt == 'image/png'
+  >>> from z3c.sharedmimeinfo.mimetype import MIMEType
+
+We can create MIMEType objects specifying media and subtype as two arguments
+or as argument in the "media/subtype" form.
+
+Here's how to use it with single argument::
+
+  >>> mt = MIMEType('text/plain')
+  >>> mt
+  <MIMEType text/plain>
+  >>> IMIMEType.providedBy(mt)
   True
-  >>> mt == u'image/png'
-  True
-  >>> 'image/png' == mt 
-  True
-  >>> u'image/png' == mt 
-  True
 
-Of course, it can also be compared to other IMIMEType objects::
+Here's how to use passing separate media and subtype arguments::
 
-  >>> mt2 = z3c.sharedmimeinfo.lookup('image/jpeg')
-  >>> mt == mt2
-  False
+  >>> MIMEType('image', 'png')
+  <MIMEType image/png>
 
-Let's use some internal API to create a second instance of image/png IMIMEType
-object and try to compare it with the first one::
+Note, that the IMIMETypes objects are cached, so if you you'll create another
+object for the same mime type, you'll get the same object::
 
-  >>> from z3c.sharedmimeinfo.mimetype import _MIMEType, MIME_TYPES
-  >>> del MIME_TYPES[('image', 'png')]
-  >>> mt3 = _MIMEType('image', 'png')
-  >>> mt is not mt3
+  >>> MIMEType('text/plain') is mt
   True
-  >>> mt == mt3
-  True

Modified: Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/__init__.py
===================================================================
--- Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/__init__.py	2009-09-08 16:41:00 UTC (rev 103650)
+++ Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/__init__.py	2009-09-08 17:06:03 UTC (rev 103651)
@@ -14,16 +14,7 @@
 """
 $Id$
 """
-from zope.interface import moduleProvides
-from z3c.sharedmimeinfo.interfaces import IConvenienceAPI
 from z3c.sharedmimeinfo.utility import globalMIMETypesUtility
 
-
-from z3c.sharedmimeinfo.mimetype import lookup
-
 def getType(filename=None, file=None):
     return globalMIMETypesUtility.getType(filename, file)
-
-
-moduleProvides(IConvenienceAPI)
-__all__ = tuple(IConvenienceAPI)

Modified: Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/interfaces.py
===================================================================
--- Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/interfaces.py	2009-09-08 16:41:00 UTC (rev 103650)
+++ Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/interfaces.py	2009-09-08 17:06:03 UTC (rev 103651)
@@ -55,27 +55,3 @@
         title=u'Title',
         required=True,
         readonly=True)
-
-    def __str__():
-        """Return a ``media/subtype`` presentation of mime type"""
-
-    def __cmp__(string_or_mimetype):
-        """Mime type objects should be comparable to strings and other types"""
-
-
-class IConvenienceAPI(Interface):
-    """Convenience API to be provided by the __init__ module."""
-    
-    def getType(filename=None, file=None):
-        """Guess content type either by file name or contents or both
-        
-        See IMIMETypesUtility.getType documentation.
-        """
-    
-    def lookup(media, subtype=None):
-        """Return a IMIMEType object for given string representation.
-        
-        If ``media`` argument is in the "media/subtype" form, then the
-        ``subtype`` argument should't be specified and will be extracted
-        from the ``media`` argument.
-        """

Modified: Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/magic.py
===================================================================
--- Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/magic.py	2009-09-08 16:41:00 UTC (rev 103650)
+++ Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/magic.py	2009-09-08 17:06:03 UTC (rev 103651)
@@ -15,7 +15,7 @@
 
 $Id$
 """
-from z3c.sharedmimeinfo.mimetype import lookup
+from z3c.sharedmimeinfo.mimetype import MIMEType
 
 
 class MagicDB(object):
@@ -41,7 +41,7 @@
                 raise Exception('Malformed section heading')
             pri, tname = shead[1:-2].split(':')
             pri = int(pri)
-            mtype = lookup(tname)
+            mtype = MIMEType(tname)
 
             ents = self.types.setdefault(pri, [])
             magictype = MagicType(mtype)

Modified: Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/mimetype.py
===================================================================
--- Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/mimetype.py	2009-09-08 16:41:00 UTC (rev 103650)
+++ Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/mimetype.py	2009-09-08 17:06:03 UTC (rev 103651)
@@ -30,40 +30,25 @@
 msgfactory = MessageFactory('shared-mime-info')
 mimeTypesTranslationDomain = SimpleTranslationDomain('shared-mime-info')
 
-MIME_TYPES = {}
+_mime_type_cache = {}
 
+class MIMEType(unicode):
+    """Single MIME type representation"""
 
-def lookup(media, subtype=None):
-    """Lookup an IMIMEType object.
+    implements(IMIMEType)
     
-    Either a pair of arguments (media and subtype) or single argument in
-    the ``media/subtype`` form can be used.
-    """
-    
-    if subtype is None and '/' in media:
-        media, subtype = media.split('/', 1)
-    if (media, subtype) not in MIME_TYPES:
-        MIME_TYPES[(media, subtype)] = _MIMEType(media, subtype)
-    return MIME_TYPES[(media, subtype)]
+    __slots__ = ('_media', '_subtype', '_title')
 
+    def __new__(cls, media, subtype=None):
+        if subtype is None and '/' in media:
+            media, subtype = media.split('/', 1)
 
-class _MIMEType(object):
-    """Single MIME type representation
-    
-    Never create these objects using this class, use the ``lookup`` function
-    defined above instead.
-    """
-
-    implements(IMIMEType)
-
-    _title = None
-
-    def __init__(self, media, subtype):
-        assert media and '/' not in media
-        assert subtype and '/' not in subtype
-        assert (media, subtype) not in MIME_TYPES
-        self.media = media
-        self.subtype = subtype
+        if (media, subtype) in _mime_type_cache:
+            return _mime_type_cache[(media, subtype)]
+        obj = super(MIMEType, cls).__new__(cls, media+'/'+subtype)
+        obj._media = media
+        obj._subtype = subtype
+        obj._title = None
         for path in iterDataPaths(os.path.join('mime', media, subtype + '.xml')):
             doc = minidom.parse(path)
             if doc is None:
@@ -73,21 +58,15 @@
                 lang = comment.getAttributeNS(XML_NAMESPACE, 'lang')
                 msgid = '%s/%s' % (media, subtype)
                 if not lang:
-                    self._title = msgfactory(msgid, default=data)
+                    obj._title = msgfactory(msgid, default=data)
                 else:
                     mimeTypesTranslationDomain.messages[(lang, msgid)] = data
+        _mime_type_cache[(media, subtype)] = obj
+        return obj
 
-    @property
-    def title(self):
-        return self._title or unicode(self)
+    title = property(lambda self:self._title or unicode(self))
+    media = property(lambda self:self._media)
+    subtype = property(lambda self:self._subtype)
 
-    def __str__(self):
-        return self.media + '/' + self.subtype
-
     def __repr__(self):
-        return '<%s %s/%s>' % (self.__class__.__name__, self.media, self.subtype)
-
-    def __cmp__(self, other):
-        if IMIMEType.providedBy(other):
-            other = str(other)
-        return cmp(str(self), other)
+        return '<%s %s>' % (self.__class__.__name__, str(self))

Modified: Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/utility.py
===================================================================
--- Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/utility.py	2009-09-08 16:41:00 UTC (rev 103650)
+++ Sandbox/nadako/z3c.sharedmimeinfo/trunk/src/z3c/sharedmimeinfo/utility.py	2009-09-08 17:06:03 UTC (rev 103651)
@@ -23,7 +23,7 @@
 from zope.interface import implements
 
 from z3c.sharedmimeinfo.magic import MagicDB
-from z3c.sharedmimeinfo.mimetype import lookup
+from z3c.sharedmimeinfo.mimetype import MIMEType
 from z3c.sharedmimeinfo.util import iterDataPaths
 from z3c.sharedmimeinfo.interfaces import IMIMETypesUtility
 
@@ -60,7 +60,7 @@
             line = line[:-1]
     
             type_name, pattern = line.split(':', 1)
-            mtype = lookup(type_name)
+            mtype = MIMEType(type_name)
     
             if pattern.startswith('*.'):
                 rest = pattern[2:]
@@ -132,11 +132,11 @@
             type = self.getTypeByContents(file, max_priority=80)
         
         if not type:
-            type = lookup('application', 'octet-stream')
+            type = MIMEType('application', 'octet-stream')
             if file:
                 file.seek(0, 0)
                 if not findBinary(file.read(32)):
-                    type = lookup('text', 'plain')
+                    type = MIMEType('text', 'plain')
 
         return type
 



More information about the checkins mailing list