@@ -80,22 +80,37 @@ def quality_and_fitness_parsed(mime_type, parsed_ranges):
80
80
"""
81
81
best_fitness = - 1
82
82
best_fit_q = 0
83
- (target_type , target_subtype , target_params ) = \
83
+ (target_type , target_subtype , target_params ) = \
84
84
parse_media_range (mime_type )
85
+
85
86
for (type , subtype , params ) in parsed_ranges :
86
- type_match = (type == target_type or
87
- type == '*' or
88
- target_type == '*' )
89
- subtype_match = (subtype == target_subtype or
90
- subtype == '*' or
91
- target_subtype == '*' )
87
+
88
+ # check if the type and the subtype match
89
+ type_match = (
90
+ type in (target_type , '*' ) or
91
+ target_type == '*'
92
+ )
93
+ subtype_match = (
94
+ subtype in (target_subtype , '*' ) or
95
+ target_subtype == '*'
96
+ )
97
+
98
+ # if they do, assess the "fitness" of this mime_type
92
99
if type_match and subtype_match :
93
- param_matches = reduce (lambda x , y : x + y , [1 for (key , value ) in
94
- target_params .items () if key != 'q' and
95
- key in params and value == params [key ]], 0 )
96
- fitness = (type == target_type ) and 100 or 0
97
- fitness += (subtype == target_subtype ) and 10 or 0
100
+
101
+ # 100 points if the type matches w/o a wildcard
102
+ fitness = type == target_type and 100 or 0
103
+
104
+ # 10 points if the subtype matches w/o a wildcard
105
+ fitness += subtype == target_subtype and 10 or 0
106
+
107
+ # 1 bonus point for each matching param besides "q"
108
+ param_matches = sum ([
109
+ 1 for (key , value ) in target_params .items ()
110
+ if key != 'q' and key in params and value == params [key ]
111
+ ])
98
112
fitness += param_matches
113
+
99
114
if fitness > best_fitness :
100
115
best_fitness = fitness
101
116
best_fit_q = params ['q' ]
@@ -156,15 +171,19 @@ def best_match(supported, header):
156
171
weighted_matches = []
157
172
pos = 0
158
173
for mime_type in supported :
159
- weighted_matches .append ((quality_and_fitness_parsed (mime_type ,
160
- parsed_header ), pos , mime_type ))
174
+ weighted_matches .append ((
175
+ quality_and_fitness_parsed (mime_type , parsed_header ),
176
+ pos ,
177
+ mime_type
178
+ ))
161
179
pos += 1
162
180
weighted_matches .sort ()
163
181
164
182
return weighted_matches [- 1 ][0 ][0 ] and weighted_matches [- 1 ][2 ] or ''
165
183
166
184
167
185
def _filter_blank (i ):
186
+ """Return all non-empty items in the list."""
168
187
for s in i :
169
188
if s .strip ():
170
189
yield s
0 commit comments