only show new curriculum if present
[edumed.git] / api / handlers.py
1 # -*- coding: utf-8 -*-
2 import json
3
4 from django.contrib.sites.models import Site
5 from django.core.urlresolvers import reverse
6 from django.utils.functional import lazy
7 from piston.handler import BaseHandler
8 from piston.utils import rc
9
10 from catalogue.forms import LessonImportForm
11 from catalogue.models import Lesson
12
13 API_BASE = EDUMED_BASE = MEDIA_BASE = lazy(
14     lambda: u'https://' + Site.objects.get_current().domain, unicode)()
15
16
17 class LessonDetails(object):
18     """Custom fields used for representing Lessons."""
19
20     @classmethod
21     def href(cls, lesson):
22         """ Returns an URI for a Lesson in the API. """
23         return API_BASE + reverse("api_lesson", args=[lesson.slug])
24
25     @classmethod
26     def url(cls, lesson):
27         """ Returns Lesson's URL on the site. """
28         return EDUMED_BASE + lesson.get_absolute_url()
29
30
31 class LessonDetailHandler(BaseHandler, LessonDetails):
32     """ Main handler for Lesson objects.
33
34     Responsible for single Lesson details.
35     """
36     allowed_methods = ['GET']
37     fields = ['title', 'url']
38
39     def read(self, request, lesson):
40         """ Returns details of a lesson, identified by a slug. """
41         try:
42             return Lesson.objects.get(slug=lesson)
43         except Lesson.DoesNotExist:
44             return rc.NOT_FOUND
45
46
47 class LessonsHandler(LessonDetailHandler):
48     allowed_methods = ('GET', 'POST')
49     model = Lesson
50     fields = ['href', 'title', 'url']
51
52     def create(self, request, *args, **kwargs):
53         if not request.user.has_perm('catalogue.add_lesson'):
54             return rc.FORBIDDEN
55
56         data = json.loads(request.POST.get('data'))
57         form = LessonImportForm(data)
58         if form.is_valid():
59             form.save()
60             return rc.CREATED
61         else:
62             return rc.NOT_FOUND