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