Fix for unclickable cites in admin.
[wolnelektury.git] / apps / api / emitters.py
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.
4 #
5 """
6 Wrappers for piston Emitter classes.
7
8 When outputting a queryset of selected models, instead of returning
9 XML or JSON stanzas, SSI include statements are returned.
10
11 """
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
17
18
19 class SsiQS(object):
20     """A wrapper for QuerySet that won't serialize."""
21
22     def __init__(self, queryset):
23         self.queryset = queryset
24
25     def __unicode__(self):
26         raise TypeError("This is not serializable.")
27
28     def get_ssis(self, emitter_format):
29         """Yields SSI include statements for the queryset."""
30         url_pattern = reverse('api_include',
31                 kwargs={'model': self.queryset.model.__name__.lower(),
32                     'pk': '0000',
33                     'emitter_format': emitter_format,
34                     'lang': get_language(),
35                     })
36         for instance in self.queryset:
37             yield "<!--#include file='%s'-->" % url_pattern.replace('0000',
38                     str(instance.pk))
39
40
41 class SsiEmitterMixin(object):
42     def construct(self):
43         if isinstance(self.data, QuerySet) and self.data.model in (Book,
44                 Fragment, Tag):
45             return SsiQS(self.data)
46         else:
47             return super(SsiEmitterMixin, self).construct()
48
49
50 class SsiJsonEmitter(SsiEmitterMixin, JSONEmitter):
51     def render(self, request):
52         try:
53             return super(SsiJsonEmitter, self).render(request)
54         except TypeError:
55             return '[%s]' % ",".join(self.construct().get_ssis('json'))
56
57 Emitter.register('json', SsiJsonEmitter, 'application/json; charset=utf-8')
58
59
60 class SsiXmlEmitter(SsiEmitterMixin, XMLEmitter):
61     def render(self, request):
62         try:
63             return super(SsiXmlEmitter, self).render(request)
64         except TypeError:
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'))
68
69 Emitter.register('xml', SsiXmlEmitter, 'text/xml; charset=utf-8')
70