Skip to content

Commit 0f99d5f

Browse files
committed
Merge pull request #2420 from mrpau/hotfix/add-mimeparse-py
Add `mimeparse.py` from `nalanda-rct3` because `tastypie` needs it.
2 parents d6c1d1b + e29c1fb commit 0f99d5f

File tree

1 file changed

+168
-0
lines changed

1 file changed

+168
-0
lines changed

python-packages/mimeparse.py

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
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 the
5+
HTTP specification [RFC 2616] for a complete explanation.
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 its component parts.
11+
- parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q'
12+
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 be
16+
pre-parsed.
17+
- best_match(): Choose the mime-type with the highest quality ('q')
18+
from a list of candidates.
19+
"""
20+
from functools import reduce
21+
22+
__version__ = '0.1.4'
23+
__author__ = 'Joe Gregorio'
24+
__email__ = 'joe@bitworking.org'
25+
__license__ = 'MIT License'
26+
__credits__ = ''
27+
28+
29+
def parse_mime_type(mime_type):
30+
"""Parses a mime-type into its component parts.
31+
32+
Carves up a mime-type and returns a tuple of the (type, subtype, params)
33+
where 'params' is a dictionary of all the parameters for the media range.
34+
For example, the media range 'application/xhtml;q=0.5' would get parsed
35+
into:
36+
37+
('application', 'xhtml', {'q', '0.5'})
38+
"""
39+
parts = mime_type.split(';')
40+
params = dict([tuple([s.strip() for s in param.split('=', 1)])
41+
for param in parts[1:]
42+
])
43+
full_type = parts[0].strip()
44+
# Java URLConnection class sends an Accept header that includes a
45+
# single '*'. Turn it into a legal wildcard.
46+
if full_type == '*':
47+
full_type = '*/*'
48+
(type, subtype) = full_type.split('/')
49+
50+
return (type.strip(), subtype.strip(), params)
51+
52+
53+
def parse_media_range(range):
54+
"""Parse a media-range into its component parts.
55+
56+
Carves up a media range and returns a tuple of the (type, subtype,
57+
params) where 'params' is a dictionary of all the parameters for the media
58+
range. For example, the media range 'application/*;q=0.5' would get parsed
59+
into:
60+
61+
('application', '*', {'q', '0.5'})
62+
63+
In addition this function also guarantees that there is a value for 'q'
64+
in the params dictionary, filling it in with a proper default if
65+
necessary.
66+
"""
67+
(type, subtype, params) = parse_mime_type(range)
68+
if not 'q' in params or not params['q'] or \
69+
not float(params['q']) or float(params['q']) > 1\
70+
or float(params['q']) < 0:
71+
params['q'] = '1'
72+
73+
return (type, subtype, params)
74+
75+
76+
def fitness_and_quality_parsed(mime_type, parsed_ranges):
77+
"""Find the best match for a mime-type amongst parsed media-ranges.
78+
79+
Find the best match for a given mime-type against a list of media_ranges
80+
that have already been parsed by parse_media_range(). Returns a tuple of
81+
the fitness value and the value of the 'q' quality parameter of the best
82+
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
83+
'parsed_ranges' must be a list of parsed media ranges.
84+
"""
85+
best_fitness = -1
86+
best_fit_q = 0
87+
(target_type, target_subtype, target_params) =\
88+
parse_media_range(mime_type)
89+
for (type, subtype, params) in parsed_ranges:
90+
type_match = (type == target_type or
91+
type == '*' or
92+
target_type == '*')
93+
subtype_match = (subtype == target_subtype or
94+
subtype == '*' or
95+
target_subtype == '*')
96+
if type_match and subtype_match:
97+
param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in
98+
list(target_params.items()) if key != 'q' and
99+
key in params and value == params[key]], 0)
100+
fitness = (type == target_type) and 100 or 0
101+
fitness += (subtype == target_subtype) and 10 or 0
102+
fitness += param_matches
103+
if fitness > best_fitness:
104+
best_fitness = fitness
105+
best_fit_q = params['q']
106+
107+
return best_fitness, float(best_fit_q)
108+
109+
110+
def quality_parsed(mime_type, parsed_ranges):
111+
"""Find the best match for a mime-type amongst parsed media-ranges.
112+
113+
Find the best match for a given mime-type against a list of media_ranges
114+
that have already been parsed by parse_media_range(). Returns the 'q'
115+
quality parameter of the best match, 0 if no match was found. This function
116+
bahaves the same as quality() except that 'parsed_ranges' must be a list of
117+
parsed media ranges. """
118+
119+
return fitness_and_quality_parsed(mime_type, parsed_ranges)[1]
120+
121+
122+
def quality(mime_type, ranges):
123+
"""Return the quality ('q') of a mime-type against a list of media-ranges.
124+
125+
Returns the quality 'q' of a mime-type when compared against the
126+
media-ranges in ranges. For example:
127+
128+
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
129+
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
130+
0.7
131+
132+
"""
133+
parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]
134+
135+
return quality_parsed(mime_type, parsed_ranges)
136+
137+
138+
def best_match(supported, header):
139+
"""Return mime-type with the highest quality ('q') from list of candidates.
140+
141+
Takes a list of supported mime-types and finds the best match for all the
142+
media-ranges listed in header. The value of header must be a string that
143+
conforms to the format of the HTTP Accept: header. The value of 'supported'
144+
is a list of mime-types. The list of supported mime-types should be sorted
145+
in order of increasing desirability, in case of a situation where there is
146+
a tie.
147+
148+
>>> best_match(['application/xbel+xml', 'text/xml'],
149+
'text/*;q=0.5,*/*; q=0.1')
150+
'text/xml'
151+
"""
152+
split_header = _filter_blank(header.split(','))
153+
parsed_header = [parse_media_range(r) for r in split_header]
154+
weighted_matches = []
155+
pos = 0
156+
for mime_type in supported:
157+
weighted_matches.append((fitness_and_quality_parsed(mime_type,
158+
parsed_header), pos, mime_type))
159+
pos += 1
160+
weighted_matches.sort()
161+
162+
return weighted_matches[-1][0][1] and weighted_matches[-1][2] or ''
163+
164+
165+
def _filter_blank(i):
166+
for s in i:
167+
if s.strip():
168+
yield s

0 commit comments

Comments
 (0)