<commit_before>import logging
from collections import defaultdict
from operator import or_

import celery
from django.shortcuts import get_object_or_404

from rest_framework import (
    generics,
    parsers,
)
from rest_framework.response import Response

from core.exceptions import (
    ResourceConflict,
    BadRequest,
)

from volumes.api import VolumeListAPIView
from volumes.models import Volume
from blueprints.models import Blueprint
from cloud.providers.base import BaseCloudProvider

from . import tasks, models, serializers

logger = logging.getLogger(__name__)


class StackListAPIView(generics.ListCreateAPIView):
    '''
    TODO: Add docstring
    '''
    model = models.Stack
    serializer_class = serializers.StackSerializer
    parser_classes = (parsers.JSONParser,)

    def get_queryset(self):
        return self.request.user.stacks.all()

    def create(self, request, *args, **kwargs):
        '''
        Overriding create method to build roles and metadata objects for this Stack
        as well as generating the salt-cloud map that will be used to launch
        machines
        '''
        # make sure the user has a public key or they won't be able to SSH
        # later
        if not request.user.settings.public_key:
            raise BadRequest('You have not added a public key to your user '
                             'profile and will not be able to SSH in to any '
                             'machines. Please update your user profile '
                             'before continuing.')

        # Validate data
        errors = {}
        blueprint_id = request.DATA.pop('blueprint', '')
        title = request.DATA.get('title', '')
        description = request.DATA.get('description', '')
        properties = request.DATA.get('properties', {})

        # check for required blueprint
        if not blueprint_id:
            errors.setdefault('blueprint', []).append('This field is required.')
        else:
            try:
                blueprint = Blueprint.objects.get(pk=blueprint_id,
                                                  owner=request.user)
            except Blueprint.DoesNotExist:
                errors.setdefault('blueprint', []).append(
                    'Blueprint with id {0} does not exist.'.format(blueprint_id)
                )
            except ValueError:
                errors.setdefault('blueprint', []).append(
                    'This field must be an integer ID of an existing blueprint.'
                )

        if not title:
            errors.setdefault('title', []).append('This field is required.')

        if not description:
            errors.setdefault('description', []).append('This field is required.')

        # check for duplicates
        if models.Stack.objects.filter(owner=self.request.user, title=title).count():
            errors.setdefault('title', []).append(
                'A Stack with this title already exists in your account.'
            )
<commit_msg>PI-199: Auto generates stack title or description if not provided by the user<commit_after>import logging
from collections import defaultdict
from datetime import datetime
from operator import or_

import celery
from django.shortcuts import get_object_or_404

from rest_framework import (
    generics,
    parsers,
)
from rest_framework.response import Response

from core.exceptions import (
    ResourceConflict,
    BadRequest,
)

from volumes.api import VolumeListAPIView
from volumes.models import Volume
from blueprints.models import Blueprint
from cloud.providers.base import BaseCloudProvider

from . import tasks, models, serializers

logger = logging.getLogger(__name__)


class StackListAPIView(generics.ListCreateAPIView):
    '''
    TODO: Add docstring
    '''
    model = models.Stack
    serializer_class = serializers.StackSerializer
    parser_classes = (parsers.JSONParser,)

    def get_queryset(self):
        return self.request.user.stacks.all()

    def create(self, request, *args, **kwargs):
        '''
        Overriding create method to build roles and metadata objects for this Stack
        as well as generating the salt-cloud map that will be used to launch
        machines
        '''
        # make sure the user has a public key or they won't be able to SSH
        # later
        if not request.user.settings.public_key:
            raise BadRequest('You have not added a public key to your user '
                             'profile and will not be able to SSH in to any '
                             'machines. Please update your user profile '
                             'before continuing.')

        # Validate data
        errors = {}
        blueprint_id = request.DATA.pop('blueprint', '')
        title = request.DATA.get('title', '')
        description = request.DATA.get('description', '')
        properties = request.DATA.get('properties', {})

        # check for required blueprint
        if not blueprint_id:
            errors.setdefault('blueprint', []).append('This field is required.')
        else:
            try:
                blueprint = Blueprint.objects.get(pk=blueprint_id,
                                                  owner=request.user)
            except Blueprint.DoesNotExist:
                errors.setdefault('blueprint', []).append(
                    'Blueprint with id {0} does not exist.'.format(blueprint_id)
                )
            except ValueError:
                errors.setdefault('blueprint', []).append(
                    'This field must be an integer ID of an existing blueprint.'
                )

        # Generate the title and/or description if not provided by user 
        if not title and not description:
            extra_description = '(Title and description'
        elif not title:
            extra_description = '(Title'
        elif not description:
            extra_description = '(Description'
        else:
            extra_description = ''
        if extra_description:
            extra_description += ' auto generated from Blueprint {0})'.format(blueprint.pk)

        if not title:
            request.DATA['title'] = '{0} ({1})'.format(
                blueprint.title,
                datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
            )

        if not description:
            description = blueprint.description
        request.DATA['description'] = description + ' {0}'.format(extra_description)

        # check for duplicates
        if models.Stack.objects.filter(owner=self.request.user, title=title).count():
            errors.setdefault('title', []).append(
                'A Stack with this title already exists in your account.'
            )

{'fraction_non_alphanumeric': 0.08550074738415546, 'fraction_numerical': 0.002242152466367713, 'mean_word_length': 2.1193473193473196, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4786841', 'n_tokens_mistral': 1681, 'n_tokens_neox': 1622, 'n_words': 528}