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 '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.
15 """
16
17 __version__ = "0.1.1"
18 __author__ = 'Joe Gregorio'
19 __email__ = "joe@bitworking.org"
20 __credits__ = ""
21
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
27 get parsed into:
28
29 ('application', 'xhtml', {'q', '0.5'})
30 """
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)
36
56
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. """
65 best_fitness = -1
66 best_match = ""
67 best_fit_q = 0
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']
82
83 return float(best_fit_q)
84
86 """Returns the quality 'q' of a mime_type when compared
87 against the media-ranges in ranges. For example:
88
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')
90 0.7
91
92 """
93 parsed_ranges = [parse_media_range(r) for r in ranges.split(",")]
94 return quality_parsed(mime_type, parsed_ranges)
95
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
101 mime-types.
102
103 >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1')
104 'text/xml'
105 """
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 ''
111
112 if __name__ == "__main__":
113 import unittest
114
116
124
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))
133
135 mime_types_supported = ['application/xbel+xml', 'application/xml']
136
137 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml'), 'application/xbel+xml')
138
139 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml; q=1'), 'application/xbel+xml')
140
141 self.assertEqual(best_match(mime_types_supported, 'application/xml; q=1'), 'application/xml')
142
143 self.assertEqual(best_match(mime_types_supported, 'application/*; q=1'), 'application/xml')
144
145 self.assertEqual(best_match(mime_types_supported, '*/*'), 'application/xml')
146
147 mime_types_supported = ['application/xbel+xml', 'text/xml']
148
149 self.assertEqual(best_match(mime_types_supported, 'text/*;q=0.5,*/*; q=0.1'), 'text/xml')
150
151 self.assertEqual(best_match(mime_types_supported, 'text/html,application/atom+xml; q=0.9'), '')
152
154 mime_types_supported = ['image/*', 'application/xml']
155
156 self.assertEqual(best_match(mime_types_supported, 'image/png'), 'image/*')
157
158 self.assertEqual(best_match(mime_types_supported, 'image/*'), 'image/*')
159
160 unittest.main()
161