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 the
5 HTTP specification [RFC 2616] for a complete explanation.
7 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
10 - parse_mime_type(): Parses a mime-type into its component parts.
11 - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q'
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 be
17 - best_match(): Choose the mime-type with the highest quality ('q')
18 from a list of candidates.
22 __author__
= 'Joe Gregorio'
23 __email__
= 'joe@bitworking.org'
24 __license__
= 'MIT License'
28 def parse_mime_type(mime_type
):
29 """Parses a mime-type into its component parts.
31 Carves up a mime-type and returns a tuple of the (type, subtype, params)
32 where 'params' is a dictionary of all the parameters for the media range.
33 For example, the media range 'application/xhtml;q=0.5' would get parsed
36 ('application', 'xhtml', {'q', '0.5'})
38 parts
= mime_type
.split(';')
39 params
= dict([tuple([s
.strip() for s
in param
.split('=', 1)])\
40 for param
in parts
[1:]
42 full_type
= parts
[0].strip()
43 # Java URLConnection class sends an Accept header that includes a
44 # single '*'. Turn it into a legal wildcard.
47 (type, subtype
) = full_type
.split('/')
49 return (type.strip(), subtype
.strip(), params
)
52 def parse_media_range(range):
53 """Parse a media-range into its component parts.
55 Carves up a media range and returns a tuple of the (type, subtype,
56 params) where 'params' is a dictionary of all the parameters for the media
57 range. For example, the media range 'application/*;q=0.5' would get parsed
60 ('application', '*', {'q', '0.5'})
62 In addition this function also guarantees that there is a value for 'q'
63 in the params dictionary, filling it in with a proper default if
66 (type, subtype
, params
) = parse_mime_type(range)
67 if 'q' not in params
or not params
['q'] or \
68 not float(params
['q']) or float(params
['q']) > 1\
69 or float(params
['q']) < 0:
72 return (type, subtype
, params
)
75 def fitness_and_quality_parsed(mime_type
, parsed_ranges
):
76 """Find the best match for a mime-type amongst parsed media-ranges.
78 Find the best match for a given mime-type against a list of media_ranges
79 that have already been parsed by parse_media_range(). Returns a tuple of
80 the fitness value and the value of the 'q' quality parameter of the best
81 match, or (-1, 0) if no match was found. Just as for quality_parsed(),
82 'parsed_ranges' must be a list of parsed media ranges.
86 (target_type
, target_subtype
, target_params
) =\
87 parse_media_range(mime_type
)
88 for (type, subtype
, params
) in parsed_ranges
:
89 type_match
= (type == target_type
or\
92 subtype_match
= (subtype
== target_subtype
or\
94 target_subtype
== '*')
95 if type_match
and subtype_match
:
96 param_matches
= sum([1 for (key
, value
) in \
97 target_params
.items() if key
!= 'q' and \
98 key
in params
and value
== params
[key
]], 0)
99 fitness
= (type == target_type
) and 100 or 0
100 fitness
+= (subtype
== target_subtype
) and 10 or 0
101 fitness
+= param_matches
102 if fitness
> best_fitness
:
103 best_fitness
= fitness
104 best_fit_q
= params
['q']
106 return best_fitness
, float(best_fit_q
)
109 def quality_parsed(mime_type
, parsed_ranges
):
110 """Find the best match for a mime-type amongst parsed media-ranges.
112 Find the best match for a given mime-type against a list of media_ranges
113 that have already been parsed by parse_media_range(). Returns the 'q'
114 quality parameter of the best match, 0 if no match was found. This function
115 bahaves the same as quality() except that 'parsed_ranges' must be a list of
116 parsed media ranges. """
118 return fitness_and_quality_parsed(mime_type
, parsed_ranges
)[1]
121 def quality(mime_type
, ranges
):
122 """Return the quality ('q') of a mime-type against a list of media-ranges.
124 Returns the quality 'q' of a mime-type when compared against the
125 media-ranges in ranges. For example:
127 >>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
128 text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
132 parsed_ranges
= [parse_media_range(r
) for r
in ranges
.split(',')]
134 return quality_parsed(mime_type
, parsed_ranges
)
137 def best_match(supported
, header
):
138 """Return mime-type with the highest quality ('q') from list of candidates.
140 Takes a list of supported mime-types and finds the best match for all the
141 media-ranges listed in header. The value of header must be a string that
142 conforms to the format of the HTTP Accept: header. The value of 'supported'
143 is a list of mime-types. The list of supported mime-types should be sorted
144 in order of increasing desirability, in case of a situation where there is
147 >>> best_match(['application/xbel+xml', 'text/xml'],
148 'text/*;q=0.5,*/*; q=0.1')
151 split_header
= _filter_blank(header
.split(','))
152 parsed_header
= [parse_media_range(r
) for r
in split_header
]
153 weighted_matches
= []
155 for mime_type
in supported
:
156 weighted_matches
.append((fitness_and_quality_parsed(mime_type
,
157 parsed_header
), pos
, mime_type
))
159 weighted_matches
.sort()
161 return weighted_matches
[-1][0][1] and weighted_matches
[-1][2] or ''
164 def _filter_blank(i
):