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.conf import settings
13 from django.core.urlresolvers import reverse
14 from django.db.models.query import QuerySet
15 from piston.emitters import Emitter, XMLEmitter, JSONEmitter
16 from catalogue.models import Book, Fragment, Tag
17 from django.utils.translation import get_language
21 """A wrapper for QuerySet that won't serialize."""
23 def __init__(self, queryset):
24 self.queryset = queryset
26 def __unicode__(self):
27 raise TypeError("This is not serializable.")
29 def get_ssis(self, emitter_format):
30 """Yields SSI include statements for the queryset."""
31 url_pattern = reverse(
34 'model': self.queryset.model.__name__.lower(),
36 'emitter_format': emitter_format,
37 'lang': get_language(),
39 for instance in self.queryset:
40 yield "<!--#include file='%s'-->" % url_pattern.replace('0000', str(instance.pk))
43 class SsiEmitterMixin(object):
45 ssify_api = getattr(settings, 'SSIFY_API', True)
46 if ssify_api and isinstance(self.data, QuerySet) and self.data.model in (Book, Fragment, Tag):
47 return SsiQS(self.data)
49 return super(SsiEmitterMixin, self).construct()
52 class SsiJsonEmitter(SsiEmitterMixin, JSONEmitter):
53 def render(self, request):
55 return super(SsiJsonEmitter, self).render(request)
57 return '[%s]' % ",".join(self.construct().get_ssis('json'))
59 Emitter.register('json', SsiJsonEmitter, 'application/json; charset=utf-8')
62 class SsiXmlEmitter(SsiEmitterMixin, XMLEmitter):
63 def render(self, request):
65 return super(SsiXmlEmitter, self).render(request)
67 return '<?xml version="1.0" encoding="utf-8"?>\n' \
68 '<response><resource>%s</resource></response>' % \
69 '</resource><resource>'.join(self.construct().get_ssis('xml'))
71 Emitter.register('xml', SsiXmlEmitter, 'text/xml; charset=utf-8')