Skip to content

Instantly share code, notes, and snippets.

@scott2b
Created February 14, 2013 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scott2b/4956582 to your computer and use it in GitHub Desktop.
Save scott2b/4956582 to your computer and use it in GitHub Desktop.
Override the HTTP_ACCEPT header with _accept parameter in Django. Taken from Django Snippets: http://djangosnippets.org/snippets/1042/
def parse_accept_header(accept):
"""Parse the Accept header *accept*, returning a list with pairs of
(media_type, q_value), ordered by q values.
"""
result = []
for media_range in accept.split(","):
parts = media_range.split(";")
media_type = parts.pop(0)
media_params = []
q = 1.0
for part in parts:
(key, value) = part.lstrip().split("=", 1)
if key == "q":
q = float(value)
else:
media_params.append((key, value))
result.append((media_type, tuple(media_params), q))
result.sort(lambda x, y: -cmp(x[2], y[2]))
return result
class AcceptMiddleware(object):
def process_request(self, request):
if '_accept' in request.GET:
param = request.GET['_accept'].replace(' ', '+')
accept = parse_accept_header(param)
request.accept_header = param
else:
accept = parse_accept_header(request.META.get("HTTP_ACCEPT", ""))
request.accept_header = request.META.get('HTTP_ACCEPT', '')
request.accept = accept
request.accepted_types = map(lambda (t, p, q): t, accept)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment