Statistics
| Branch: | Tag: | Revision:

root / helpers.py @ b65b1281

History | View | Annotate | Download (1 kB)

1 5c812d1b Faidon Liambotis
# vim: ts=4 sts=4 et ai sw=4 fileencoding=utf-8
2 5c812d1b Faidon Liambotis
#
3 5c812d1b Faidon Liambotis
# Copyright © 2010 Greek Research and Technology Network
4 5c812d1b Faidon Liambotis
#
5 5c812d1b Faidon Liambotis
6 5c812d1b Faidon Liambotis
import re
7 5c812d1b Faidon Liambotis
from django.conf.urls.defaults import url
8 5c812d1b Faidon Liambotis
9 5c812d1b Faidon Liambotis
_accept_re = re.compile(r'([^\s;,]+)(?:[^,]*?;\s*q=(\d*(?:\.\d+)?))?')
10 5c812d1b Faidon Liambotis
11 5c812d1b Faidon Liambotis
def parse_accept_header(value):
12 5c812d1b Faidon Liambotis
    """Parse an HTTP Accept header
13 5c812d1b Faidon Liambotis

14 5c812d1b Faidon Liambotis
    Returns an ordered by quality list of tuples (value, quality)
15 5c812d1b Faidon Liambotis
    """
16 5c812d1b Faidon Liambotis
    if not value:
17 5c812d1b Faidon Liambotis
        return []
18 5c812d1b Faidon Liambotis
19 5c812d1b Faidon Liambotis
    result = []
20 5c812d1b Faidon Liambotis
    for match in _accept_re.finditer(value):
21 5c812d1b Faidon Liambotis
        quality = match.group(2)
22 5c812d1b Faidon Liambotis
        if not quality:
23 5c812d1b Faidon Liambotis
            quality = 1
24 5c812d1b Faidon Liambotis
        else:
25 5c812d1b Faidon Liambotis
            quality = max(min(float(quality), 1), 0)
26 5c812d1b Faidon Liambotis
        result.append((match.group(1), quality))
27 5c812d1b Faidon Liambotis
28 5c812d1b Faidon Liambotis
    # sort by quality
29 5c812d1b Faidon Liambotis
    result.sort(key=lambda x: x[1])
30 5c812d1b Faidon Liambotis
31 5c812d1b Faidon Liambotis
    return result
32 5c812d1b Faidon Liambotis
33 5c812d1b Faidon Liambotis
def url_with_format(regex, *args, **kwargs):
34 5c812d1b Faidon Liambotis
    """
35 5c812d1b Faidon Liambotis
    An extended url() that adds an .json/.xml suffix to the end to avoid DRY
36 5c812d1b Faidon Liambotis
    """
37 5c812d1b Faidon Liambotis
    if regex[-1] == '$' and regex[-2] != '\\':
38 5c812d1b Faidon Liambotis
        regex = regex[:-1]
39 5c812d1b Faidon Liambotis
    regex = regex + r'(\.(?P<emitter_format>json|xml))?$'
40 5c812d1b Faidon Liambotis
    return url(regex, *args, **kwargs)