<commit_before>from restlib2.resources import Resource
from avocado.models import DataContext, DataView
from ..decorators import check_auth


def _resolve_object(klass, key, request, attrs=None):
    """Resolves the appropriate object for use from the request. This is for
    DataView or DataContext objects only.
    """
    # Attempt to derive the `attrs` from the request
    if attrs is None:
        if request.method == 'POST':
            attrs = request.data.get(key)
        elif request.method == 'GET':
            attrs = request.GET.get(key)

    # If attrs were supplied or derived from the request, validate them
    # and return as is. This provides support for one-off queries via POST
    # or GET.
    if isinstance(attrs, dict):
        klass.validate(attrs)
        return klass(json=attrs)

    # Ignore archived objects..
    kwargs = {
        'archived': False,
    }

    # If an authenticated user made the request, filter by the user or
    # fallback to an active session key.
    if hasattr(request, 'user') and request.user.is_authenticated():
        kwargs['user'] = request.user
    else:
        # If not session has been created, this is a cookie-less user agent
        # which is most likely a bot or a non-browser client (e.g. cURL).
        if request.session.session_key is None:
            return klass()
        kwargs['session_key'] = request.session.session_key

    # Assume it is a primary key and fallback to the sesssion
    try:
        kwargs['pk'] = int(attrs)
    except (ValueError, TypeError):
        kwargs['session'] = True

    try:
        return klass.objects.get(**kwargs)
    except klass.DoesNotExist:
        pass

    return klass()


class BaseResource(Resource):
    param_defaults = {}

    @check_auth
    def __call__(self, *args, **kwargs):
        return super(BaseResource, self).__call__(*args, **kwargs)

    def get_params(self, request):
        params = request.GET.copy()
        for param, default in self.param_defaults.items():
            params.setdefault(param, default)
        return params


class ContextViewBaseResource(BaseResource):
    def get_context(self, request, attrs=None):
        "Returns a DataContext object based on `attrs` or the request."
        return _resolve_object(DataContext, 'context', request, attrs)

    def get_view(self, request, attrs=None):
        "Returns a DataView object based on `attrs` or the request."
        return _resolve_object(DataView, 'view', request, attrs)<commit_msg>Add support for CORS<commit_after>from django.conf import settings
from restlib2.resources import Resource
from avocado.models import DataContext, DataView
from ..decorators import check_auth

CORS_ENABLED = getattr(settings, 'SERRANO_CORS_ENABLED', True)
CORS_ORIGIN = getattr(settings, 'SERRANO_CORS_ORIGIN', '*')


def _resolve_object(klass, key, request, attrs=None):
    """Resolves the appropriate object for use from the request. This is for
    DataView or DataContext objects only.
    """
    # Attempt to derive the `attrs` from the request
    if attrs is None:
        if request.method == 'POST':
            attrs = request.data.get(key)
        elif request.method == 'GET':
            attrs = request.GET.get(key)

    # If attrs were supplied or derived from the request, validate them
    # and return as is. This provides support for one-off queries via POST
    # or GET.
    if isinstance(attrs, dict):
        klass.validate(attrs)
        return klass(json=attrs)

    # Ignore archived objects..
    kwargs = {
        'archived': False,
    }

    # If an authenticated user made the request, filter by the user or
    # fallback to an active session key.
    if hasattr(request, 'user') and request.user.is_authenticated():
        kwargs['user'] = request.user
    else:
        # If not session has been created, this is a cookie-less user agent
        # which is most likely a bot or a non-browser client (e.g. cURL).
        if request.session.session_key is None:
            return klass()
        kwargs['session_key'] = request.session.session_key

    # Assume it is a primary key and fallback to the sesssion
    try:
        kwargs['pk'] = int(attrs)
    except (ValueError, TypeError):
        kwargs['session'] = True

    try:
        return klass.objects.get(**kwargs)
    except klass.DoesNotExist:
        pass

    return klass()


class BaseResource(Resource):
    param_defaults = {}

    @check_auth
    def __call__(self, *args, **kwargs):
        return super(BaseResource, self).__call__(*args, **kwargs)

    def get_params(self, request):
        params = request.GET.copy()
        for param, default in self.param_defaults.items():
            params.setdefault(param, default)
        return params

    def process_response(self, request, response):
        response = super(BaseResource, self).process_response(request, response)
        if CORS_ENABLED:
            response['Access-Control-Allow-Origin'] = CORS_ORIGIN
            response['Access-Control-Allow-Methods'] = ', '.join(self.allowed_methods)
        return response


class ContextViewBaseResource(BaseResource):
    def get_context(self, request, attrs=None):
        "Returns a DataContext object based on `attrs` or the request."
        return _resolve_object(DataContext, 'context', request, attrs)

    def get_view(self, request, attrs=None):
        "Returns a DataView object based on `attrs` or the request."
        return _resolve_object(DataView, 'view', request, attrs)
{'fraction_non_alphanumeric': 0.09367639065048015, 'fraction_numerical': 0.0003623844899438304, 'mean_word_length': 2.870967741935484, '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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4300959', 'n_tokens_mistral': 1543, 'n_tokens_neox': 1535, 'n_words': 519}