3 This module provides basic functions for handling mime-types. It can handle
4 matching mime-types against a list of media-ranges. See section 14.1 of
5 the HTTP specification [RFC 2616] for a complete explaination.
7 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
10 - parse_mime_type(): Parses a mime-type into it's component parts.
11 - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter.
12 - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges.
13 - quality_parsed(): Just like quality() except the second parameter must be pre-parsed.
14 - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates.
18 __author__ = 'Joe Gregorio'
19 __email__ = "joe@bitworking.org"
22 def parse_mime_type(mime_type):
23 """Carves up a mime_type and returns a tuple of the
24 (type, subtype, params) where 'params' is a dictionary
25 of all the parameters for the media range.
26 For example, the media range 'application/xhtml;q=0.5' would
29 ('application', 'xhtml', {'q', '0.5'})
31 parts = mime_type.split(";")
32 params = dict([tuple([s.strip() for s in param.split("=")])\
33 for param in parts[1:] ])
34 (type, subtype) = parts[0].split("/")
35 return (type.strip(), subtype.strip(), params)
37 def parse_media_range(range):
38 """Carves up a media range and returns a tuple of the
39 (type, subtype, params) where 'params' is a dictionary
40 of all the parameters for the media range.
41 For example, the media range 'application/*;q=0.5' would
44 ('application', '*', {'q', '0.5'})
46 In addition this function also guarantees that there
47 is a value for 'q' in the params dictionary, filling it
48 in with a proper default if necessary.
50 (type, subtype, params) = parse_mime_type(range)
51 if not params.has_key('q') or not params['q'] or \
52 not float(params['q']) or float(params['q']) > 1\
53 or float(params['q']) < 0:
55 return (type, subtype, params)
57 def quality_parsed(mime_type, parsed_ranges):
58 """Find the best match for a given mime_type against
59 a list of media_ranges that have already been
60 parsed by parse_media_range(). Returns the
61 'q' quality parameter of the best match, 0 if no
62 match was found. This function bahaves the same as quality()
63 except that 'parsed_ranges' must be a list of
64 parsed media ranges. """
68 (target_type, target_subtype, target_params) =\
69 parse_media_range(mime_type)
70 for (type, subtype, params) in parsed_ranges:
71 param_matches = reduce(lambda x, y: x+y, [1 for (key, value) in \
72 target_params.iteritems() if key != 'q' and \
73 params.has_key(key) and value == params[key]], 0)
74 if (type == target_type or type == '*' or target_type == '*') and \
75 (subtype == target_subtype or subtype == '*' or target_subtype == '*'):
76 fitness = (type == target_type) and 100 or 0
77 fitness += (subtype == target_subtype) and 10 or 0
78 fitness += param_matches
79 if fitness > best_fitness:
80 best_fitness = fitness
81 best_fit_q = params['q']
83 return float(best_fit_q)
85 def quality(mime_type, ranges):
86 """Returns the quality 'q' of a mime_type when compared
87 against the media-ranges in ranges. For example:
89 >>> 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')
93 parsed_ranges = [parse_media_range(r) for r in ranges.split(",")]
94 return quality_parsed(mime_type, parsed_ranges)
96 def best_match(supported, header):
97 """Takes a list of supported mime-types and finds the best
98 match for all the media-ranges listed in header. The value of
99 header must be a string that conforms to the format of the
100 HTTP Accept: header. The value of 'supported' is a list of
103 >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1')
106 parsed_header = [parse_media_range(r) for r in header.split(",")]
107 weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type)\
108 for mime_type in supported]
109 weighted_matches.sort()
110 return weighted_matches[-1][0] and weighted_matches[-1][1] or ''
112 if __name__ == "__main__":
115 class TestMimeParsing(unittest.TestCase):
117 def test_parse_media_range(self):
118 self.assert_(('application', 'xml', {'q': '1'}) == parse_media_range('application/xml;q=1'))
119 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml'))
120 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml;q='))
121 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml ; q='))
122 self.assertEqual(('application', 'xml', {'q': '1', 'b': 'other'}), parse_media_range('application/xml ; q=1;b=other'))
123 self.assertEqual(('application', 'xml', {'q': '1', 'b': 'other'}), parse_media_range('application/xml ; q=2;b=other'))
125 def test_rfc_2616_example(self):
126 accept = "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5"
127 self.assertEqual(1, quality("text/html;level=1", accept))
128 self.assertEqual(0.7, quality("text/html", accept))
129 self.assertEqual(0.3, quality("text/plain", accept))
130 self.assertEqual(0.5, quality("image/jpeg", accept))
131 self.assertEqual(0.4, quality("text/html;level=2", accept))
132 self.assertEqual(0.7, quality("text/html;level=3", accept))
134 def test_best_match(self):
135 mime_types_supported = ['application/xbel+xml', 'application/xml']
137 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml'), 'application/xbel+xml')
138 # direct match with a q parameter
139 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml; q=1'), 'application/xbel+xml')
140 # direct match of our second choice with a q parameter
141 self.assertEqual(best_match(mime_types_supported, 'application/xml; q=1'), 'application/xml')
142 # match using a subtype wildcard
143 self.assertEqual(best_match(mime_types_supported, 'application/*; q=1'), 'application/xml')
144 # match using a type wildcard
145 self.assertEqual(best_match(mime_types_supported, '*/*'), 'application/xml')
147 mime_types_supported = ['application/xbel+xml', 'text/xml']
148 # match using a type versus a lower weighted subtype
149 self.assertEqual(best_match(mime_types_supported, 'text/*;q=0.5,*/*; q=0.1'), 'text/xml')
150 # fail to match anything
151 self.assertEqual(best_match(mime_types_supported, 'text/html,application/atom+xml; q=0.9'), '')
153 def test_support_wildcards(self):
154 mime_types_supported = ['image/*', 'application/xml']
155 # match using a type wildcard
156 self.assertEqual(best_match(mime_types_supported, 'image/png'), 'image/*')
157 # match using a wildcard for both requested and supported
158 self.assertEqual(best_match(mime_types_supported, 'image/*'), 'image/*')