<commit_before>from django.http import HttpResponseBadRequest, HttpResponseForbidden, HttpResponse

from ..simplified import PermissionDenied, SimplifiedException
from restview import RestfulView
from serializers import serializers, SerializableResult
from readform import ReadForm



class HttpResponseCreated(HttpResponse):
    status_code = 201


def _extjswrap(data, use_extjshacks, success=True, total=None):
    if use_extjshacks:
        result = dict(items = data)
        if total != None:
            result['total'] = total
        result['success'] = success
        return result
    else:
        if total == None:
            return data
        else:
            return dict(items=data, total=total)

class ErrorMsgSerializableResult(SerializableResult):
    def __init__(self, errormessage, httpresponsecls):
        super(ErrorMsgSerializableResult, self).__init__(dict(errormessages=[errormessage]),
                                                         httpresponsecls=httpresponsecls)

class ForbiddenSerializableResult(ErrorMsgSerializableResult):
    def __init__(self):
        super(ForbiddenSerializableResult, self).__init__('Forbidden',
                                                          HttpResponseForbidden)

class FormErrorSerializableResult(SerializableResult):
    def __init__(self, form, use_extjshacks):
        fielderrors = dict(form.errors)
        non_field_errors = list(form.non_field_errors())
        result = dict(fielderrors=fielderrors, errormessages=non_field_errors)
        result = _extjswrap(result, use_extjshacks, success=False)
        super(FormErrorSerializableResult, self).__init__(result, httpresponsecls=HttpResponseBadRequest)


class ModelRestfulView(RestfulView):
    """
    :class:`ModelRestfulView` is used in conjunction with the
    :class:`restful_modelapi`-decorator to autogenerate a RESTful
    interface for a simplified class (see :ref:`simplified`).
    """
    @classmethod
    def filter_urlmap(cls, itemdct):
        if not hasattr(cls._meta, 'urlmap'):
            return itemdct
        for fieldname, mapping in cls._meta.urlmap.iteritems():
            url = mapping.restfulcls.get_rest_url(itemdct[mapping.idfield])
            itemdct[fieldname] = url
        return itemdct

    @classmethod
    def filter_resultitem(cls, itemdct):
        return cls.filter_urlmap(itemdct)


    def _extjswrapshortcut(self, data, success=True, total=None):
        return _extjswrap(data, self.use_extjshacks, success, total)

    def restultqry_to_list(self, qryresultwrapper):
        return [self.__class__.filter_resultitem(itemdct) \
                for itemdct in qryresultwrapper]

    def _create_or_replace(self, instance=None):
        data = serializers.deserialize(self.comformat, self.request.raw_post_data)
        form = self.__class__.EditForm(data, instance=instance)
        result = None
        if form.is_valid():
            try:
                if instance == None:
                    id = self._meta.simplified.create(self.request.user, **form.cleaned_data)
                else:
                    id = self._meta.simplified.update(self.request.user, instance.pk, **form.cleaned_data)
            except PermissionDenied:
                return ForbiddenSerializableResult()

            data['id'] = id
            result = self._extjswrapshortcut(data)
            if instance == None:
                return SerializableResult(result, httpresponsecls=HttpResponseCreated)
            else:<commit_msg>restful.modelrestview: Unused variable.<commit_after>from django.http import HttpResponseBadRequest, HttpResponseForbidden, HttpResponse

from ..simplified import PermissionDenied, SimplifiedException
from restview import RestfulView
from serializers import serializers, SerializableResult
from readform import ReadForm



class HttpResponseCreated(HttpResponse):
    status_code = 201


def _extjswrap(data, use_extjshacks, success=True, total=None):
    if use_extjshacks:
        result = dict(items = data)
        if total != None:
            result['total'] = total
        result['success'] = success
        return result
    else:
        if total == None:
            return data
        else:
            return dict(items=data, total=total)

class ErrorMsgSerializableResult(SerializableResult):
    def __init__(self, errormessage, httpresponsecls):
        super(ErrorMsgSerializableResult, self).__init__(dict(errormessages=[errormessage]),
                                                         httpresponsecls=httpresponsecls)

class ForbiddenSerializableResult(ErrorMsgSerializableResult):
    def __init__(self):
        super(ForbiddenSerializableResult, self).__init__('Forbidden',
                                                          HttpResponseForbidden)

class FormErrorSerializableResult(SerializableResult):
    def __init__(self, form, use_extjshacks):
        fielderrors = dict(form.errors)
        non_field_errors = list(form.non_field_errors())
        result = dict(fielderrors=fielderrors, errormessages=non_field_errors)
        result = _extjswrap(result, use_extjshacks, success=False)
        super(FormErrorSerializableResult, self).__init__(result, httpresponsecls=HttpResponseBadRequest)


class ModelRestfulView(RestfulView):
    """
    :class:`ModelRestfulView` is used in conjunction with the
    :class:`restful_modelapi`-decorator to autogenerate a RESTful
    interface for a simplified class (see :ref:`simplified`).
    """
    @classmethod
    def filter_urlmap(cls, itemdct):
        if not hasattr(cls._meta, 'urlmap'):
            return itemdct
        for fieldname, mapping in cls._meta.urlmap.iteritems():
            url = mapping.restfulcls.get_rest_url(itemdct[mapping.idfield])
            itemdct[fieldname] = url
        return itemdct

    @classmethod
    def filter_resultitem(cls, itemdct):
        return cls.filter_urlmap(itemdct)


    def _extjswrapshortcut(self, data, success=True, total=None):
        return _extjswrap(data, self.use_extjshacks, success, total)

    def restultqry_to_list(self, qryresultwrapper):
        return [self.__class__.filter_resultitem(itemdct) \
                for itemdct in qryresultwrapper]

    def _create_or_replace(self, instance=None):
        data = serializers.deserialize(self.comformat, self.request.raw_post_data)
        form = self.__class__.EditForm(data, instance=instance)
        if form.is_valid():
            try:
                if instance == None:
                    id = self._meta.simplified.create(self.request.user, **form.cleaned_data)
                else:
                    id = self._meta.simplified.update(self.request.user, instance.pk, **form.cleaned_data)
            except PermissionDenied:
                return ForbiddenSerializableResult()

            data['id'] = id
            result = self._extjswrapshortcut(data)
            if instance == None:
                return SerializableResult(result, httpresponsecls=HttpResponseCreated)
            else:
{'fraction_non_alphanumeric': 0.08219567690557451, 'fraction_numerical': 0.0008532423208191126, 'mean_word_length': 2.8389737991266375, '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': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1985590', 'n_tokens_mistral': 1945, 'n_tokens_neox': 1910, 'n_words': 399}