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(';') 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
- A wrapper around cache_page making it optional by rixx 2 days, 2 hours ago
- Treat empty value on DateRangeFilter as a filter for non filled dates by kmmbvnr 1 month, 1 week ago
- Django Settings Assignment Expressions aka Walrus Operator example by webology 2 months, 1 week ago
- codigo alto nivel by MrRocklion 4 months, 1 week ago
- Load template from specific app by Krzysiek555 4 months, 4 weeks ago