1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 Wrappers for piston Emitter classes.
8 When outputting a queryset of selected models, instead of returning
9 XML or JSON stanzas, SSI include statements are returned.
12 from django.core.urlresolvers import reverse
13 from django.db.models.query import QuerySet
14 from piston.emitters import Emitter, XMLEmitter, JSONEmitter
15 from catalogue.models import Book, Fragment, Tag
16 from django.utils.translation import get_language
20 """A wrapper for QuerySet that won't serialize."""
22 def __init__(self, queryset):
23 self.queryset = queryset
25 def __unicode__(self):
26 raise TypeError("This is not serializable.")
28 def get_ssis(self, emitter_format):
29 """Yields SSI include statements for the queryset."""
30 url_pattern = reverse(
33 'model': self.queryset.model.__name__.lower(),
35 'emitter_format': emitter_format,
36 'lang': get_language(),
38 for instance in self.queryset:
39 yield "<!--#include file='%s'-->" % url_pattern.replace('0000', str(instance.pk))
42 class SsiEmitterMixin(object):
44 if isinstance(self.data, QuerySet) and self.data.model in (Book, Fragment, Tag):
45 return SsiQS(self.data)
47 return super(SsiEmitterMixin, self).construct() # WTF
50 class SsiJsonEmitter(SsiEmitterMixin, JSONEmitter):
51 def render(self, request):
53 return super(SsiJsonEmitter, self).render(request)
55 return '[%s]' % ",".join(self.construct().get_ssis('json'))
57 Emitter.register('json', SsiJsonEmitter, 'application/json; charset=utf-8')
60 class SsiXmlEmitter(SsiEmitterMixin, XMLEmitter):
61 def render(self, request):
63 return super(SsiXmlEmitter, self).render(request)
65 return '<?xml version="1.0" encoding="utf-8"?>\n' \
66 '<response><resource>%s</resource></response>' % \
67 '</resource><resource>'.join(self.construct().get_ssis('xml'))
69 Emitter.register('xml', SsiXmlEmitter, 'text/xml; charset=utf-8')