Skip to content

Instantly share code, notes, and snippets.

@jdp
Created March 4, 2014 20:50
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 jdp/9355352 to your computer and use it in GitHub Desktop.
Save jdp/9355352 to your computer and use it in GitHub Desktop.
content negotiation mixin for django class based views
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