raven (for sentry.io)
[wolnelektury.git] / src / 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.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
18
19
20 class SsiQS(object):
21     """A wrapper for QuerySet that won't serialize."""
22
23     def __init__(self, queryset):
24         self.queryset = queryset
25
26     def __unicode__(self):
27         raise TypeError("This is not serializable.")
28
29     def get_ssis(self, emitter_format):
30         """Yields SSI include statements for the queryset."""
31         url_pattern = reverse(
32             'api_include',
33             kwargs={
34                 'model': self.queryset.model.__name__.lower(),
35                 'pk': '0000',
36                 'emitter_format': emitter_format,
37                 'lang': get_language(),
38             })
39         for instance in self.queryset:
40             yield "<!--#include file='%s'-->" % url_pattern.replace('0000', str(instance.pk))
41
42
43 class SsiEmitterMixin(object):
44     def construct(self):
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)
48         else:
49             return super(SsiEmitterMixin, self).construct()
50
51
52 class SsiJsonEmitter(SsiEmitterMixin, JSONEmitter):
53     def render(self, request):
54         try:
55             return super(SsiJsonEmitter, self).render(request)
56         except TypeError:
57             return '[%s]' % ",".join(self.construct().get_ssis('json'))
58
59 Emitter.register('json', SsiJsonEmitter, 'application/json; charset=utf-8')
60
61
62 class SsiXmlEmitter(SsiEmitterMixin, XMLEmitter):
63     def render(self, request):
64         try:
65             return super(SsiXmlEmitter, self).render(request)
66         except TypeError:
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'))
70
71 Emitter.register('xml', SsiXmlEmitter, 'text/xml; charset=utf-8')