Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Ticket #1842: preferred_type.py

File preferred_type.py, 1.8 KB (added by chrisz, 4 years ago)

Determination of the preferred media type

Line 
1
2
3def preferred_type(accept_header):
4    """Return the most preferred media tpye or range from the accept header."""
5    best_type = accept_header
6    best_q = 0
7    for range in accept_header.split(','):
8        range = range.split(';')
9        this_type = range.pop(0)
10        for param in range:
11            param = param.split('=', 1)
12            if param[0].strip() == 'q':
13                try:
14                    q = float(param[1])
15                    if not 0 < q <= 1:
16                        raise ValueError
17                except (IndexError, ValueError):
18                    q = 0
19                break
20        else:
21            q = 1
22        if q > best_q:
23            this_type = this_type.strip()
24            if this_type:
25                best_type = this_type
26                if q == 1:
27                    break
28                best_q = q
29    return best_type.strip()
30
31
32def test_preferred_type():
33    t = preferred_type
34    assert t('text/html') == 'text/html'
35    assert t('text/html;level=1') == 'text/html'
36    assert t('audio/*, audio/basic') == 'audio/*'
37    assert t('audio/*; q=0.2, audio/basic') == 'audio/basic'
38    assert t('audio/*, audio/basic; q=0.2') == 'audio/*'
39    assert t('''text/plain; q=0.5, text/html,
40        text/x-dvi; q=0.8, text/x-c''') == 'text/html'
41    assert t('''text/plain; q=0.5, text/html; q=0.1,
42        text/x-dvi; q=0.8, text/x-c''') == 'text/x-c'
43    assert t('''text/plain; q=0.5, text/html; q=0.1,
44        text/x-dvi; q=0.8, text/x-c; q=0.5''') == 'text/x-dvi'
45    assert t('''text/*, text/html; q=0.1,
46        text/x-dvi; q=0.8, text/x-c''') == 'text/*'
47    assert t('text/*, text/html, text/html;level=1, */*') == 'text/*'
48    assert t('''text/*;q=0.3, text/html;q=0.7, text/html;level=1,
49        text/html;level=2;q=0.4, */*;q=0.5''') == 'text/html'
50