<commit_before>import collections
import re

import furl
from django.core.urlresolvers import resolve, reverse, NoReverseMatch
from django.core.exceptions import ImproperlyConfigured
from django.http.request import QueryDict
from rest_framework import exceptions
from rest_framework import serializers as ser
from rest_framework.fields import SkipField
from rest_framework.fields import get_attribute as get_nested_attributes

from api.base import utils
from api.base.exceptions import InvalidQueryStringError
from api.base.exceptions import Conflict
from api.base.exceptions import JSONAPIException
from api.base.exceptions import TargetNotSupportedError
from api.base.exceptions import RelationshipPostMakesNoChanges
from api.base.settings import BULK_SETTINGS
from api.base.utils import absolute_reverse, extend_querystring_params, get_user_auth, extend_querystring_if_key_exists
from framework.auth import core as auth_core
from website import settings
from website import util as website_utils
from website.models import Node
from website.util.sanitize import strip_html


def format_relationship_links(related_link=None, self_link=None, rel_meta=None, self_meta=None):
    """
    Properly handles formatting of self and related links according to JSON API.

    Removes related or self link, if none.
    """

    ret = {'links': {}}

    if related_link:
        ret['links'].update({
            'related': {
                'href': related_link or {},
                'meta': rel_meta or {}
            }
        })

    if self_link:
        ret['links'].update({
            'self': {
                'href': self_link or {},
                'meta': self_meta or {}
            }
        })

    return ret


def is_anonymized(request):
    private_key = request.query_params.get('view_only', None)
    return website_utils.check_private_key_for_anonymized_link(private_key)


class ShowIfVersion(ser.Field):
    """
    Skips the field if the specified request version is not after a feature's earliest supported version,
    or not before the feature's latest supported version.
    """

    def __init__(self, field, min_version, max_version, **kwargs):
        super(ShowIfVersion, self).__init__(**kwargs)
        self.field = field
        self.required = field.required
        self.read_only = field.read_only
        self.min_version = min_version
        self.max_version = max_version

    def get_attribute(self, instance):
        request = self.context.get('request')
        if request and utils.is_deprecated(request.version, self.min_version, self.max_version):
            raise SkipField
        return self.field.get_attribute(instance)

    def bind(self, field_name, parent):
        super(ShowIfVersion, self).bind(field_name, parent)
        self.field.bind(field_name, self)

    def to_representation(self, value):
        if getattr(self.field.root, 'child', None):
            self.field.parent = self.field.root.child
        else:
            self.field.parent = self.field.root
        return self.field.to_representation(value)

    def to_internal_value(self, data):
        return self.field.to_internal_value(data)


class HideIfRegistration(ser.Field):
    """
    If node is a registration, this field will return None.
    """

    def __init__(self, field, **kwargs):
        super(HideIfRegistration, self).__init__(**kwargs)
        self.field = field
        self.source = field.source
        self.required = field.required
        self.read_only = field.read_only

    def get_attribute(self, instance):
        if instance.is_registration:
            if isinstance(self.field, RelationshipField):
                raise SkipField
            else:
                return None
        return self.field.get_attribute(instance)

    def bind(self, field_name, parent):
        super(HideIfRegistration, self).bind(field_name, parent)<commit_msg>Add to_esi_representation to ShowIfVersion serializer field<commit_after>import collections
import re

import furl
from django.core.urlresolvers import resolve, reverse, NoReverseMatch
from django.core.exceptions import ImproperlyConfigured
from django.http.request import QueryDict
from rest_framework import exceptions
from rest_framework import serializers as ser
from rest_framework.fields import SkipField
from rest_framework.fields import get_attribute as get_nested_attributes

from api.base import utils
from api.base.exceptions import InvalidQueryStringError
from api.base.exceptions import Conflict
from api.base.exceptions import JSONAPIException
from api.base.exceptions import TargetNotSupportedError
from api.base.exceptions import RelationshipPostMakesNoChanges
from api.base.settings import BULK_SETTINGS
from api.base.utils import absolute_reverse, extend_querystring_params, get_user_auth, extend_querystring_if_key_exists
from framework.auth import core as auth_core
from website import settings
from website import util as website_utils
from website.models import Node
from website.util.sanitize import strip_html


def format_relationship_links(related_link=None, self_link=None, rel_meta=None, self_meta=None):
    """
    Properly handles formatting of self and related links according to JSON API.

    Removes related or self link, if none.
    """

    ret = {'links': {}}

    if related_link:
        ret['links'].update({
            'related': {
                'href': related_link or {},
                'meta': rel_meta or {}
            }
        })

    if self_link:
        ret['links'].update({
            'self': {
                'href': self_link or {},
                'meta': self_meta or {}
            }
        })

    return ret


def is_anonymized(request):
    private_key = request.query_params.get('view_only', None)
    return website_utils.check_private_key_for_anonymized_link(private_key)


class ShowIfVersion(ser.Field):
    """
    Skips the field if the specified request version is not after a feature's earliest supported version,
    or not before the feature's latest supported version.
    """

    def __init__(self, field, min_version, max_version, **kwargs):
        super(ShowIfVersion, self).__init__(**kwargs)
        self.field = field
        self.required = field.required
        self.read_only = field.read_only
        self.min_version = min_version
        self.max_version = max_version

    def get_attribute(self, instance):
        request = self.context.get('request')
        if request and utils.is_deprecated(request.version, self.min_version, self.max_version):
            raise SkipField
        return self.field.get_attribute(instance)

    def bind(self, field_name, parent):
        super(ShowIfVersion, self).bind(field_name, parent)
        self.field.bind(field_name, self)

    def to_representation(self, value):
        if getattr(self.field.root, 'child', None):
            self.field.parent = self.field.root.child
        else:
            self.field.parent = self.field.root
        return self.field.to_representation(value)

    def to_esi_representation(self, value, envelope='data'):
        if getattr(self.field.root, 'child', None):
            self.field.parent = self.field.root.child
        else:
            self.field.parent = self.field.root
        return self.field.to_esi_representation(value, envelope)

    def to_internal_value(self, data):
        return self.field.to_internal_value(data)


class HideIfRegistration(ser.Field):
    """
    If node is a registration, this field will return None.
    """

    def __init__(self, field, **kwargs):
        super(HideIfRegistration, self).__init__(**kwargs)
        self.field = field
        self.source = field.source
        self.required = field.required
        self.read_only = field.read_only

    def get_attribute(self, instance):
        if instance.is_registration:
            if isinstance(self.field, RelationshipField):
                raise SkipField
            else:
                return None
        return self.field.get_attribute(instance)

    def bind(self, field_name, parent):
        super(HideIfRegistration, self).bind(field_name, parent)
{'fraction_non_alphanumeric': 0.08156246161405233, 'fraction_numerical': 0.0, 'mean_word_length': 3.1038306451612905, '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': '1168499', 'n_tokens_mistral': 2252, 'n_tokens_neox': 2180, 'n_words': 598}