Login

Improved Accept header middleware

Author:
ludvig.ericson
Posted:
September 10, 2008
Language:
Python
Version:
1.0
Tags:
middleware accept header
Score:
4 (after 4 ratings)

A clean and simple implementation of parsing the Accept header. It places the result in request.accepted_types.

Place this middleware anywhere in the chain, as all it does is add to the request object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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):
        accept = parse_accept_header(request.META.get("HTTP_ACCEPT", ""))
        request.accept = accept
        request.accepted_types = map(lambda (t, p, q): t, accept)

More like this

  1. Improved Accept middleware with webkit workaround by raven_nevermore 4 years, 6 months ago
  2. Accept Header Middleware by kioopi 7 years, 1 month ago
  3. Ignore HTTP Accept-Language headers by fonso 8 years ago
  4. Add Extra Headers to Test Client Requests by luftyluft 6 years, 10 months ago
  5. Multilingual site based on domain - not accept header and django_session by hermansc 3 years, 4 months ago

Comments

Please login first before commenting.