from django.http import Http404
from django.conf import settings
from django_rq import enqueue
from tastypie.resources import Resource
from tastypie import fields
from projects.models import Project
from .models import NodeTask
from .jobs import run_node_task
from .utils import logger


class NodeTaskHookResource(Resource):
    """Node task hook resource"""
    before = fields.CharField()
    after = fields.CharField()
    ref = fields.CharField()
    commits = fields.ListField()
    repository = fields.DictField()

    class Meta:
        allowed_methods = ['post']
        resource_name = 'nodes/hook'

    def obj_create(self, bundle, **kwargs):
        """Create task from received data"""
        logger.info('Node task started: {}'.format(bundle.data['ref']))
        project_name = '{}/{}'.format(
            bundle.data['repository']['owner']['name'],
            bundle.data['repository']['name'],
        )
        try:
            project = Project.objects.get(
                name=project_name, is_enabled=True, run_here=True,
            )
        except Project.DoesNotExist:
            logger.warning(
                'Project for node task not found: {}'.
                format(project_name),
            )
            raise Http404('Project not found')
        task = NodeTask.objects.create(
            project=project,
            revision=bundle.data['after'],
            branch=self._get_branch(bundle.data['ref']),
        )
        enqueue(
            run_node_task, args=(task.id,),
            timeout=settings.NODE_MAX_WAIT_TIME,
        )

    def _get_branch(self, ref):
        """Get branch from ref"""
        return ref.replace('refs/heads/', '')

@@ -765,16 +765,563 @@
 ref'%5D))%0A
+        project = self._get_project(bundle)%0A        self._create_task(bundle, project)%0A%0A    def _create_task(self, bundle, project):%0A        %22%22%22Create node task for project%22%22%22%0A        task = NodeTask.objects.create(%0A            project=project,%0A            revision=bundle.data%5B'after'%5D,%0A            branch=self._get_branch(bundle.data%5B'ref'%5D),%0A        )%0A        enqueue(%0A            run_node_task, args=(task.id,),%0A            timeout=settings.NODE_MAX_WAIT_TIME,%0A        )%0A%0A    def _get_project(self, bundle):%0A        %22%22%22Get project instance%22%22%22%0A
         
@@ -1351,16 +1351,16 @@
 format(%0A
-
         
@@ -1489,25 +1489,22 @@
         
-project =
+return
  Project
@@ -1762,32 +1762,32 @@
 ,%0A            )%0A
+
             rais
@@ -1820,307 +1820,8 @@
 nd')
-%0A        task = NodeTask.objects.create(%0A            project=project,%0A            revision=bundle.data%5B'after'%5D,%0A            branch=self._get_branch(bundle.data%5B'ref'%5D),%0A        )%0A        enqueue(%0A            run_node_task, args=(task.id,),%0A            timeout=settings.NODE_MAX_WAIT_TIME,%0A        )
 %0A%0A  

Make little refactoring