summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStefan Wojcik <wojcikstefan@gmail.com>2016-09-28 17:56:16 -0400
committerStefan Wojcik <wojcikstefan@gmail.com>2016-09-28 17:56:16 -0400
commit5443249bcddbb9e8e4f3de95f14b3a9bdc7aa3e6 (patch)
treefadce9a3600d8a14b87a4aac585aed241b27de72
parentc1e74a7660a469525ca8b3e8324c98b71dcf512b (diff)
downloadpython-mimeparse-5443249bcddbb9e8e4f3de95f14b3a9bdc7aa3e6.tar.gz
cleaner code for quality_and_fitness_parsed
-rw-r--r--mimeparse.py47
-rw-r--r--testdata.json2
2 files changed, 34 insertions, 15 deletions
diff --git a/mimeparse.py b/mimeparse.py
index 5a2cd46..0c09729 100644
--- a/mimeparse.py
+++ b/mimeparse.py
@@ -80,22 +80,37 @@ def quality_and_fitness_parsed(mime_type, parsed_ranges):
"""
best_fitness = -1
best_fit_q = 0
- (target_type, target_subtype, target_params) =\
+ (target_type, target_subtype, target_params) = \
parse_media_range(mime_type)
+
for (type, subtype, params) in parsed_ranges:
- type_match = (type == target_type or
- type == '*' or
- target_type == '*')
- subtype_match = (subtype == target_subtype or
- subtype == '*' or
- target_subtype == '*')
+
+ # check if the type and the subtype match
+ type_match = (
+ type in (target_type, '*') or
+ target_type == '*'
+ )
+ subtype_match = (
+ subtype in (target_subtype, '*') or
+ target_subtype == '*'
+ )
+
+ # if they do, assess the "fitness" of this mime_type
if type_match and subtype_match:
- param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in
- target_params.items() if key != 'q' and
- key in params and value == params[key]], 0)
- fitness = (type == target_type) and 100 or 0
- fitness += (subtype == target_subtype) and 10 or 0
+
+ # 100 points if the type matches w/o a wildcard
+ fitness = type == target_type and 100 or 0
+
+ # 10 points if the subtype matches w/o a wildcard
+ fitness += subtype == target_subtype and 10 or 0
+
+ # 1 bonus point for each matching param besides "q"
+ param_matches = sum([
+ 1 for (key, value) in target_params.items()
+ if key != 'q' and key in params and value == params[key]
+ ])
fitness += param_matches
+
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
@@ -156,8 +171,11 @@ def best_match(supported, header):
weighted_matches = []
pos = 0
for mime_type in supported:
- weighted_matches.append((quality_and_fitness_parsed(mime_type,
- parsed_header), pos, mime_type))
+ weighted_matches.append((
+ quality_and_fitness_parsed(mime_type, parsed_header),
+ pos,
+ mime_type
+ ))
pos += 1
weighted_matches.sort()
@@ -165,6 +183,7 @@ def best_match(supported, header):
def _filter_blank(i):
+ """Return all non-empty items in the list."""
for s in i:
if s.strip():
yield s
diff --git a/testdata.json b/testdata.json
index 2609f6f..7e591be 100644
--- a/testdata.json
+++ b/testdata.json
@@ -88,7 +88,7 @@
[
[
["application/xbel+xml", "application/xml"],
- "*/*", "application/xml"
+ "*/*"
],
"application/xml",
"match using a type wildcard"