<commit_before>"""
The public API
"""
import logging

from flask.views import View
from flask.app import request, json
from flask import session, make_response
from webargs import Arg
from webargs.flaskparser import FlaskParser

from app import models
from app.codereview import compare
from app.constants import API_PREFIX
from app.needs import Need
from app.utils import paginate, filter_query, create_zip

from google.appengine.ext import db, ndb

BadValueError = db.BadValueError

parser = FlaskParser()

def KeyArg(klass, **kwds):
    return Arg(ndb.Key, use=lambda c: {'pairs':[(klass, int(c))]}, **kwds)

def KeyRepeatedArg(klass, **kwds):
    def parse_list(key_list):
        staff_lst = key_list
        if not isinstance(key_list, list):
            if ',' in key_list:
                staff_lst = key_list.split(',')
            else:
                staff_lst = [key_list]
        return [ndb.Key(klass, x) for x in staff_lst]
    return Arg(None, use=parse_list, **kwds)

class APIResource(View):
    """The base class for API resources.

    Set the model for each subclass.
    """

    model = None
    web_args = {}
    key_type = int

    @property
    def name(self):
        return self.model.__name__

    def get_instance(self, key, user):
        obj = self.model.get_by_id(key)
        if not obj:
            return (404, "{resource} {key} not found".format(
                resource=self.name, key=key))

        need = Need('get')
        if not obj.can(user, need, obj):
            return need.api_response()

        return obj

    def dispatch_request(self, path, *args, **kwargs):
        meth = request.method.upper()
        user = session['user']

        if not path: # Index
            if meth == "GET":
                return self.index(user)
            elif meth == "POST":
                return self.post(user)
            assert meth in ("GET", "POST"), 'Unimplemented method %s' % meth

        if '/' not in path:
            # For now, just allow ID gets
            assert meth in ['GET', 'PUT', 'DELETE']
            meth = getattr(self, meth.lower(), None)

            assert meth is not None, 'Unimplemented method %r' % request.method
            try:
                key = self.key_type(path)
            except (ValueError, AssertionError):
                return (400,
                    "Invalid key. Needs to be of type '%s'" % self.key_type)

            inst = self.get_instance(key, user)
            if not isinstance(inst, self.model):
                return inst

            return meth(inst, user, *args, **kwargs)

        entity_id, action = path.split('/')
        try:
            key = self.key_type(entity_id)
        except (ValueError, AssertionError):
            return (400,
                "Invalid key. Needs to be of type '%s'" % self.key_type)

        meth = getattr(self, action, None)
        assert meth is not None, 'Unimplemented action %r' % action
        inst = self.get_instance(key)
        if not isinstance(inst, self.model):
            return inst

        return meth(inst, user, *args, **kwargs)

    def get(self, obj, user):
        """
        The GET HTTP method
        """
        return obj

    def put(self, obj, user):
        """
        The PUT HTTP method
        """
        need = Need('put')
        if not obj.can(user, need, obj):
            return need.api_response()

        blank_val = object()<commit_msg>Fixed dumb bug.<commit_after>"""
The public API
"""
import logging

from flask.views import View
from flask.app import request, json
from flask import session, make_response
from webargs import Arg
from webargs.flaskparser import FlaskParser

from app import models
from app.codereview import compare
from app.constants import API_PREFIX
from app.needs import Need
from app.utils import paginate, filter_query, create_zip

from google.appengine.ext import db, ndb

BadValueError = db.BadValueError

parser = FlaskParser()

def KeyArg(klass, **kwds):
    return Arg(ndb.Key, use=lambda c: {'pairs':[(klass, int(c))]}, **kwds)

def KeyRepeatedArg(klass, **kwds):
    def parse_list(key_list):
        staff_lst = key_list
        if not isinstance(key_list, list):
            if ',' in key_list:
                staff_lst = key_list.split(',')
            else:
                staff_lst = [key_list]
        return [ndb.Key(klass, x) for x in staff_lst]
    return Arg(None, use=parse_list, **kwds)

class APIResource(View):
    """The base class for API resources.

    Set the model for each subclass.
    """

    model = None
    web_args = {}
    key_type = int

    @property
    def name(self):
        return self.model.__name__

    def get_instance(self, key, user):
        obj = self.model.get_by_id(key)
        if not obj:
            return (404, "{resource} {key} not found".format(
                resource=self.name, key=key))

        need = Need('get')
        if not obj.can(user, need, obj):
            return need.api_response()

        return obj

    def dispatch_request(self, path, *args, **kwargs):
        meth = request.method.upper()
        user = session['user']

        if not path: # Index
            if meth == "GET":
                return self.index(user)
            elif meth == "POST":
                return self.post(user)
            assert meth in ("GET", "POST"), 'Unimplemented method %s' % meth

        if '/' not in path:
            # For now, just allow ID gets
            assert meth in ['GET', 'PUT', 'DELETE']
            meth = getattr(self, meth.lower(), None)

            assert meth is not None, 'Unimplemented method %r' % request.method
            try:
                key = self.key_type(path)
            except (ValueError, AssertionError):
                return (400,
                    "Invalid key. Needs to be of type '%s'" % self.key_type)

            inst = self.get_instance(key, user)
            if not isinstance(inst, self.model):
                return inst

            return meth(inst, user, *args, **kwargs)

        entity_id, action = path.split('/')
        try:
            key = self.key_type(entity_id)
        except (ValueError, AssertionError):
            return (400,
                "Invalid key. Needs to be of type '%s'" % self.key_type)

        meth = getattr(self, action, None)
        assert meth is not None, 'Unimplemented action %r' % action
        inst = self.get_instance(key, user)
        if not isinstance(inst, self.model):
            return inst

        return meth(inst, user, *args, **kwargs)

    def get(self, obj, user):
        """
        The GET HTTP method
        """
        return obj

    def put(self, obj, user):
        """
        The PUT HTTP method
        """
        need = Need('put')
        if not obj.can(user, need, obj):
            return need.api_response()

        blank_val = object()
{'fraction_non_alphanumeric': 0.10832847990681421, 'fraction_numerical': 0.0026208503203261502, 'mean_word_length': 2.0113985094256903, 'pattern_counts': {'":': 4, '<': 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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3466790', 'n_tokens_mistral': 2035, 'n_tokens_neox': 1964, 'n_words': 638}