Created
April 26, 2013 11:42
-
-
Save zacharyvoase/5466753 to your computer and use it in GitHub Desktop.
Example: Content negotiation in Django. This may be more complicated than it needs to be; it'd be simple to write a library which deals with the common cases rather than having to do the full broker registration.
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
from broker import Broker # https://github.com/zacharyvoase/broker | |
from django.core import serializers # https://docs.djangoproject.com/en/dev/topics/serialization/ | |
from django.http import HttpResponse | |
from django.shortcuts import render | |
from myapp.models import Thing | |
# This is just a library I wrote once to help do content negotiation. | |
# We define a 'renderers' for each supported content type (HTML and JSON) | |
# and then pass the list of things into that. | |
things_renderer = Broker() | |
@things_renderer.register('text/html') | |
def render_things_html(request, things): | |
return render(request, 'things/list.html', {'things': things}) | |
@things_renderer.register('application/json') | |
def render_things_json(request, things): | |
return HttpResponse(serializers.serialize('json', things), | |
content_type='application/json') | |
# The view itself: | |
def list_things(request): | |
things = Thing.objects.order_by('-created')[:20] | |
return things_renderer(request.META['HTTP_ACCEPT'], request, things) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment