Login

Accept Header Middleware

Author:
kioopi
Posted:
April 16, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

A middleware that parses the HTTP_ACCEPT header of a request.

The request gets a new method called "accepts" that takes a string and returns True if it was in the list of accepted mime-types.

It makes it possible to write views like:

def exampleview(request):
    if request.accepts('application/json'):
        # return a json representation

    if request.accepts('text/html'): 
        # return html

Please note that with this middleware the view defines the priority of the mime-types, not the order in which they where provided in the HTTP-Header.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import new

def accepts( self, mime ):
    return mime in self.accepted_types

class AcceptMiddleware(object):
    def process_request(self, request):
        acc = [a.split(';')[0] for a in request.META['HTTP_ACCEPT'].split(',')]
        setattr(request, 'accepted_types', acc )
        request.accepts = new.instancemethod(accepts, request, request.__class__)
        return None

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

ludvig.ericson (on September 10, 2008):

I'd say the new.instancemethod trickery is indeed uncalled for:

request.accepts = lambda type: type in acc

Not to mention the list comprehension. :-)

#

Please login first before commenting.