Statistics
| Branch: | Tag: | Revision:

root / helpers.py @ 5c812d1b

History | View | Annotate | Download (1 kB)

1
# vim: ts=4 sts=4 et ai sw=4 fileencoding=utf-8
2
#
3
# Copyright © 2010 Greek Research and Technology Network
4
#
5

    
6
import re
7
from django.conf.urls.defaults import url
8

    
9
_accept_re = re.compile(r'([^\s;,]+)(?:[^,]*?;\s*q=(\d*(?:\.\d+)?))?')
10

    
11
def parse_accept_header(value):
12
    """Parse an HTTP Accept header
13

14
    Returns an ordered by quality list of tuples (value, quality)
15
    """
16
    if not value:
17
        return []
18

    
19
    result = []
20
    for match in _accept_re.finditer(value):
21
        quality = match.group(2)
22
        if not quality:
23
            quality = 1
24
        else:
25
            quality = max(min(float(quality), 1), 0)
26
        result.append((match.group(1), quality))
27

    
28
    # sort by quality
29
    result.sort(key=lambda x: x[1])
30

    
31
    return result
32

    
33
def url_with_format(regex, *args, **kwargs):
34
    """
35
    An extended url() that adds an .json/.xml suffix to the end to avoid DRY
36
    """
37
    if regex[-1] == '$' and regex[-2] != '\\':
38
        regex = regex[:-1]
39
    regex = regex + r'(\.(?P<emitter_format>json|xml))?$'
40
    return url(regex, *args, **kwargs)