0001"""MIME-Type Parser
0002
0003This module provides basic functions for handling mime-types. It can handle
0004matching mime-types against a list of media-ranges. See section 14.1 of
0005the HTTP specification [RFC 2616] for a complete explaination.
0006
0007 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
0008
0009Contents:
0010 - parse_mime_type(): Parses a mime-type into it's component parts.
0011 - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter.
0012 - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges.
0013 - quality_parsed(): Just like quality() except the second parameter must be pre-parsed.
0014 - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates.
0015"""
0016
0017__version__ = "0.1"
0018__author__ = 'Joe Gregorio'
0019__email__ = "joe@bitworking.org"
0020__credits__ = ""
0021
0022def parse_mime_type(mime_type):
0023 """Carves up a mime_type and returns a tuple of the
0024 (type, subtype, params) where 'params' is a dictionary
0025 of all the parameters for the media range.
0026 For example, the media range 'application/xhtml;q=0.5' would
0027 get parsed into:
0028
0029 ('application', 'xhtml', {'q', '0.5'})
0030 """
0031 parts = mime_type.split(";")
0032 params = dict([tuple([s.strip() for s in param.split("=")]) for param in parts[1:] ])
0034 (type, subtype) = parts[0].split("/")
0035 return (type.strip(), subtype.strip(), params)
0036
0037def parse_media_range(range):
0038 """Carves up a media range and returns a tuple of the
0039 (type, subtype, params) where 'params' is a dictionary
0040 of all the parameters for the media range.
0041 For example, the media range 'application/*;q=0.5' would
0042 get parsed into:
0043
0044 ('application', '*', {'q', '0.5'})
0045
0046 In addition this function also guarantees that there
0047 is a value for 'q' in the params dictionary, filling it
0048 in with a proper default if necessary.
0049 """
0050 (type, subtype, params) = parse_mime_type(range)
0051 if not params.has_key('q') or not params['q'] or not float(params['q']) or float(params['q']) > 1 or float(params['q']) < 0:
0054 params['q'] = '1'
0055 return (type, subtype, params)
0056
0057def quality_parsed(mime_type, parsed_ranges):
0058 """Find the best match for a given mime_type against
0059 a list of media_ranges that have already been
0060 parsed by parse_media_range(). Returns the
0061 'q' quality parameter of the best match, 0 if no
0062 match was found. This function bahaves the same as quality()
0063 except that 'parsed_ranges' must be a list of
0064 parsed media ranges. """
0065 best_fitness = -1
0066 best_match = ""
0067 best_fit_q = 0
0068 (target_type, target_subtype, target_params) = parse_media_range(mime_type)
0070 for (type, subtype, params) in parsed_ranges:
0071 param_matches = sum([1 for (key, value) in target_params.iteritems() if key != 'q' and params.has_key(key) and value == params[key]])
0074 if (type == target_type or type == '*') and (subtype == target_subtype or subtype == "*"):
0076 fitness = (type == target_type) and 100 or 0
0077 fitness += (subtype == target_subtype) and 10 or 0
0078 fitness += param_matches
0079 if fitness > best_fitness:
0080 best_fitness = fitness
0081 best_fit_q = params['q']
0082
0083 return float(best_fit_q)
0084
0085def quality(mime_type, ranges):
0086 """Returns the quality 'q' of a mime_type when compared
0087 against the media-ranges in ranges. For example:
0088
0089 >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0090 0.7
0091
0092 """
0093 parsed_ranges = [parse_media_range(r) for r in ranges.split(",")]
0094 return quality_parsed(mime_type, parsed_ranges)
0095
0096def best_match(supported, header):
0097 """Takes a list of supported mime-types and finds the best
0098 match for all the media-ranges listed in header. The value of
0099 header must be a string that conforms to the format of the
0100 HTTP Accept: header. The value of 'supported' is a list of
0101 mime-types.
0102
0103 >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1')
0104 'text/xml'
0105 """
0106 parsed_header = [parse_media_range(r) for r in header.split(",")]
0107 weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type) for mime_type in supported]
0109 weighted_matches.sort()
0110 return weighted_matches[-1][0] and weighted_matches[-1][1] or ''
0111
0112if __name__ == "__main__":
0113 import unittest
0114
0115 class TestMimeParsing(unittest.TestCase):
0116
0117 def test_parse_media_range(self):
0118 self.assert_(('application', 'xml', {'q': '1'}) == parse_media_range('application/xml;q=1'))
0119 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml'))
0120 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml;q='))
0121 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml ; q='))
0122 self.assertEqual(('application', 'xml', {'q': '1', 'b': 'other'}), parse_media_range('application/xml ; q=1;b=other'))
0123 self.assertEqual(('application', 'xml', {'q': '1', 'b': 'other'}), parse_media_range('application/xml ; q=2;b=other'))
0124
0125 def test_rfc_2616_example(self):
0126 accept = "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5"
0127 self.assertEqual(1, quality("text/html;level=1", accept))
0128 self.assertEqual(0.7, quality("text/html", accept))
0129 self.assertEqual(0.3, quality("text/plain", accept))
0130 self.assertEqual(0.5, quality("image/jpeg", accept))
0131 self.assertEqual(0.4, quality("text/html;level=2", accept))
0132 self.assertEqual(0.7, quality("text/html;level=3", accept))
0133
0134 def test_best_match(self):
0135 mime_types_supported = ['application/xbel+xml', 'application/xml']
0136
0137 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml'), 'application/xbel+xml')
0138
0139 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml; q=1'), 'application/xbel+xml')
0140
0141 self.assertEqual(best_match(mime_types_supported, 'application/xml; q=1'), 'application/xml')
0142
0143 self.assertEqual(best_match(mime_types_supported, 'application/*; q=1'), 'application/xml')
0144
0145 self.assertEqual(best_match(mime_types_supported, '*/*'), 'application/xml')
0146
0147 mime_types_supported = ['application/xbel+xml', 'text/xml']
0148
0149 self.assertEqual(best_match(mime_types_supported, 'text/*;q=0.5,*/*; q=0.1'), 'text/xml')
0150
0151 self.assertEqual(best_match(mime_types_supported, 'text/html,application/atom+xml; q=0.9'), '')
0152
0153 unittest.main()