Package madrona :: Package openid :: Package utils :: Module mimeparse
[hide private]

Source Code for Module madrona.openid.utils.mimeparse

  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   
26 -def parse_mime_type(mime_type):
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
41 -def parse_media_range(range):
42 """Carves up a media range and returns a tuple of the 43 (type, subtype, params) where 'params' is a dictionary 44 of all the parameters for the media range. 45 For example, the media range 'application/*;q=0.5' would 46 get parsed into: 47 48 ('application', '*', {'q', '0.5'}) 49 50 In addition this function also guarantees that there 51 is a value for 'q' in the params dictionary, filling it 52 in with a proper default if necessary. 53 """ 54 (type, subtype, params) = parse_mime_type(range) 55 if not 'q' in params or not params['q'] or \ 56 not float(params['q']) or float(params['q']) > 1\ 57 or float(params['q']) < 0: 58 params['q'] = '1' 59 return (type, subtype, params)
60
61 -def quality_parsed(mime_type, parsed_ranges):
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
89 -def quality(mime_type, ranges):
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
101 -def best_match(supported, header):
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
120 - class TestMimeParsing(unittest.TestCase):
121
122 - def test_parse_media_range(self):
123 self.assert_(('application', 'xml', {'q': '1'}) == parse_media_range('application/xml;q=1')) 124 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml')) 125 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml;q=')) 126 self.assertEqual(('application', 'xml', {'q': '1'}), parse_media_range('application/xml ; q=')) 127 self.assertEqual(('application', 'xml', {'q': '1', 'b': 'other'}), parse_media_range('application/xml ; q=1;b=other')) 128 self.assertEqual(('application', 'xml', {'q': '1', 'b': 'other'}), parse_media_range('application/xml ; q=2;b=other'))
129
130 - def test_rfc_2616_example(self):
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
139 - def test_best_match(self):
140 mime_types_supported = ['application/xbel+xml', 'application/xml'] 141 # direct match 142 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml'), 'application/xbel+xml') 143 # direct match with a q parameter 144 self.assertEqual(best_match(mime_types_supported, 'application/xbel+xml; q=1'), 'application/xbel+xml') 145 # direct match of our second choice with a q parameter 146 self.assertEqual(best_match(mime_types_supported, 'application/xml; q=1'), 'application/xml') 147 # match using a subtype wildcard 148 self.assertEqual(best_match(mime_types_supported, 'application/*; q=1'), 'application/xml') 149 # match using a type wildcard 150 self.assertEqual(best_match(mime_types_supported, '*/*'), 'application/xml') 151 152 mime_types_supported = ['application/xbel+xml', 'text/xml'] 153 # match using a type versus a lower weighted subtype 154 self.assertEqual(best_match(mime_types_supported, 'text/*;q=0.5,*/*; q=0.1'), 'text/xml') 155 # fail to match anything 156 self.assertEqual(best_match(mime_types_supported, 'text/html,application/atom+xml; q=0.9'), '')
157
158 - def test_support_wildcards(self):
159 mime_types_supported = ['image/*', 'application/xml'] 160 # match using a type wildcard 161 self.assertEqual(best_match(mime_types_supported, 'image/png'), 'image/*') 162 # match using a wildcard for both requested and supported 163 self.assertEqual(best_match(mime_types_supported, 'image/*'), 'image/*')
164 165 unittest.main() 166