1 """MIME-Type Parser
2
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.
6
7 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
8
9 Contents:
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
12 'q' quality parameter.
13 - quality(): Determines the quality ('q') of a mime-type when
14 compared against a list of media-ranges.
15 - quality_parsed(): Just like quality() except the second parameter must
16 be pre-parsed.
17 - best_match(): Choose the mime-type with the highest quality ('q')
18 from a list of candidates.
19 """
20
21 __version__ = "0.1.1"
22 __author__ = 'Joe Gregorio'
23 __email__ = "joe@bitworking.org"
24 __credits__ = ""
25
27 """Carves up a mime_type and returns a tuple of the
28 (type, subtype, params) where 'params' is a dictionary
29 of all the parameters for the media range.
30 For example, the media range 'application/xhtml;q=0.5' would
31 get parsed into:
32
33 ('application', 'xhtml', {'q', '0.5'})
34 """
35 parts = mime_type.split(";")
36 params = dict([tuple([s.strip() for s in param.split("=")])\
37 for param in parts[1:]])
38 (type, subtype) = parts[0].split("/")
39 return (type.strip(), subtype.strip(), params)
40
60
62 """Find the best match for a given mime_type against
63 a list of media_ranges that have already been
64 parsed by parse_media_range(). Returns the
65 'q' quality parameter of the best match, 0 if no
66 match was found. This function bahaves the same as quality()
67 except that 'parsed_ranges' must be a list of
68 parsed media ranges. """
69 best_fitness = -1
70 best_match = ""
71 best_fit_q = 0
72 (target_type, target_subtype, target_params) =\
73 parse_media_range(mime_type)
74 for (type, subtype, params) in parsed_ranges:
75 param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \
76 target_params.iteritems() if key != 'q' and \
77 key in params and value == params[key]], 0)
78 if (type == target_type or type == '*' or target_type == '*') and \
79 (subtype == target_subtype or subtype == '*' or target_subtype == '*'):
80 fitness = (type == target_type) and 100 or 0
81 fitness += (subtype == target_subtype) and 10 or 0
82 fitness += param_matches
83 if fitness > best_fitness:
84 best_fitness = fitness
85 best_fit_q = params['q']
86
87 return float(best_fit_q)
88
90 """Returns the quality 'q' of a mime_type when compared
91 against the media-ranges in ranges. For example:
92
93 >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, '
94 'text/html;level=2;q=0.4, */*;q=0.5')
95 0.7
96
97 """
98 parsed_ranges = [parse_media_range(r) for r in ranges.split(",")]
99 return quality_parsed(mime_type, parsed_ranges)
100
102 """Takes a list of supported mime-types and finds the best
103 match for all the media-ranges listed in header. The value of
104 header must be a string that conforms to the format of the
105 HTTP Accept: header. The value of 'supported' is a list of
106 mime-types.
107
108 >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1')
109 'text/xml'
110 """
111 parsed_header = [parse_media_range(r) for r in header.split(",")]
112 weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type)\
113 for mime_type in supported]
114 weighted_matches.sort()
115 return weighted_matches[-1][0] and weighted_matches[-1][1] or ''
116
117 if __name__ == "__main__":
118 import unittest
119
121
129
131 accept = "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5"
132 self.assertEqual(1, quality("text/html;level=1", accept))
133 self.assertEqual(0.7, quality("text/html", accept))
134 self.assertEqual(0.3, quality("text/plain", accept))
135 self.assertEqual(0.5, quality("image/jpeg", accept))
136 self.assertEqual(0.4, quality("text/html;level=2", accept))
137 self.assertEqual(0.7, quality("text/html;level=3", accept))
138
140 mime_types_supported = ['application/xbel+xml', 'application/xml']
141
142 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml'), 'application/xbel+xml')
143
144 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml; q=1'), 'application/xbel+xml')
145
146 self.assertEqual(best_match(mime_types_supported, 'application/xml; q=1'), 'application/xml')
147
148 self.assertEqual(best_match(mime_types_supported, 'application/*; q=1'), 'application/xml')
149
150 self.assertEqual(best_match(mime_types_supported, '*/*'), 'application/xml')
151
152 mime_types_supported = ['application/xbel+xml', 'text/xml']
153
154 self.assertEqual(best_match(mime_types_supported, 'text/*;q=0.5,*/*; q=0.1'), 'text/xml')
155
156 self.assertEqual(best_match(mime_types_supported, 'text/html,application/atom+xml; q=0.9'), '')
157
159 mime_types_supported = ['image/*', 'application/xml']
160
161 self.assertEqual(best_match(mime_types_supported, 'image/png'), 'image/*')
162
163 self.assertEqual(best_match(mime_types_supported, 'image/*'), 'image/*')
164
165 unittest.main()
166