Created
March 4, 2014 20:50
-
-
Save jdp/9355352 to your computer and use it in GitHub Desktop.
content negotiation mixin for django class based views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mimeparse | |
class ContentNegotiationMixin(object): | |
def not_acceptable(self, request): | |
return HttpResponse(status=406) | |
def get_acceptable(self, request): | |
return dict(self.accepts) | |
def negotiate(self, request, *args, **kwargs): | |
acceptable = self.get_acceptable(request) | |
mime_type = mimeparse.best_match(acceptable.keys(), request.META['HTTP_ACCEPT']) | |
if mime_type in acceptable: | |
acceptor = acceptable[mime_type] | |
if isinstance(acceptor, basestring): | |
acceptor = getattr(self, acceptor) | |
return acceptor(request, *args, **kwargs) | |
return self.not_acceptable(request) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment