Commits

Konstantin Mochalov  committed feb6b84

Some refactoring

  • Participants
  • Parent commits c7125b0

Comments (0)

Files changed (1)

File tasks/views.py

 from django.core.paginator import Paginator, EmptyPage
 from django.conf import settings
 from django.shortcuts import get_object_or_404
+from django.views.decorators.http import require_http_methods
 
 from models import Task, ValidationError
 
+def _validate_and_save_task_from_api(task, data):
+    try:
+        task.update_from_api(data)
+    except ValidationError as e:
+        return HttpResponseBadRequest(str(e))
+
+    task.save()
+    return HttpResponse()
+
 def _tasks_get(request):
     page = int(request.GET.get('page', 1))
     sort_column = request.GET.get('sort_column', 'id')
 
     if (sort_column not in ['id', 'description', 'date_start'] or
             sort_order not in ['asc', 'desc']):
-        raise HttpResponseBadRequest("Invalid sort specification")
+        return HttpResponseBadRequest("Invalid sort specification")
 
     q = Task.objects.all().order_by(sort_column)
     if sort_order == 'desc':
     return HttpResponse(json.dumps(result), content_type="application/json")
 
 def _tasks_put(request):
-    task = Task()
     try:
         data = json.loads(request.body)
     except ValueError:
         return HttpResponseBadRequest("Invalid json")
 
-    try:
-        task.update_from_api(data)
-    except ValidationError as e:
-        return HttpResponseBadRequest(str(e))
-
-    task.save()
-    return HttpResponse()
+    task = Task()
+    return _validate_and_save_task_from_api(task, data)
 
 def _task_post(request, id):
     try:
         return HttpResponseBadRequest("Invalid json")
 
     task = get_object_or_404(Task, pk=id)
-
-    try:
-        task.update_from_api(data)
-        task.save()
-    except ValidationError as e:
-        return HttpResponseBadRequest(str(e))
-
-    return HttpResponse()
+    return _validate_and_save_task_from_api(task, data)
 
 def _task_delete(request, id):
     get_object_or_404(Task, pk=id).delete()
     return HttpResponse()
 
+@require_http_methods(["GET", "PUT"])
 def tasks(request):
+    """
+    Tasks view: GET returns a list of tasks, paged and sorted, PUT creates a new task
+    """
     if request.method == "GET":
         return _tasks_get(request)
     elif request.method == "PUT":
         return _tasks_put(request)
-    else:
-        return HttpResponseNotAllowed(["GET", "PUT"])
 
+@require_http_methods(["POST", "DELETE"])
 def task(request, id):
+    """
+    Single task view: POST modifies task, DELETE deletes it
+    """
     if request.method == "POST":
         return _task_post(request, id)
     elif request.method == "DELETE":    
-        return _task_delete(request, id)
-
-    else:
-        return HttpResponseNotAllowed(['PUT', 'POST', 'DELETE'])
+        return _task_delete(request, id)