<commit_before>import abc
import functools
import logging
import types
import itertools

from marnadi import descriptors, Header
from marnadi.errors import HttpError


class HandlerType(abc.ABCMeta):

    logger = logging.getLogger('marnadi')

    def __new__(mcs, name, bases, attributes):
        cls = super(HandlerType, mcs).__new__(mcs, name, bases, attributes)
        for attr_name, attr_value in attributes.iteritems():
            cls.set_descriptor_name(attr_value, attr_name)
        return cls

    def __setattr__(cls, attr_name, attr_value):
        super(HandlerType, cls).__setattr__(attr_name, attr_value)
        cls.set_descriptor_name(attr_value, attr_name)

    def __call__(cls, *args, **kwargs):
        if cls.func is not None:
            return cls.func(*args, **kwargs)
        return super(HandlerType, cls).__call__(*args, **kwargs)

    def decorator(cls, func):
        method = staticmethod(func)
        attributes = dict(func=method)
        for supported_method in cls.SUPPORTED_HTTP_METHODS:
            supported_method = supported_method.lower()
            if getattr(cls, supported_method, NotImplemented) is NotImplemented:
                attributes[supported_method] = method
        return functools.update_wrapper(
            type('', (cls, ), attributes),
            func, updated=(),
        )

    @staticmethod
    def make_string(entity):
        return '' if entity is None else unicode(entity).encode('utf-8')

    def log_exception(cls, func, exclude=None):
        @functools.wraps(func)
        def _func(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as error:
                if exclude and not isinstance(error, exclude):
                    cls.logger.exception(error)
                raise
        return _func

    def handle(cls, environ, start_response, args=(), kwargs=None):
        try:
            return cls.log_exception(cls._handle, exclude=HttpError)(
                environ, start_response, args=args, kwargs=kwargs
            )
        except HttpError:
            raise
        except Exception as error:
            cls.handle_exception(error, environ, args, kwargs)

    def _handle(cls, environ, start_response, args=(), kwargs=None):
        handler = super(HandlerType, cls).__call__(environ)
        result = handler(*args, **kwargs or {})
        if isinstance(result, types.GeneratorType):
            func = cls.log_exception(cls.make_string)
            chunks = itertools.imap(func, result)
        else:
            result = cls.make_string(result)
            chunks = (result, )
        status = handler.status
        headers = list(handler.headers.flush())
        start_response(status, headers)
        return chunks

    def handle_exception(cls, error, environ, args, kwargs):
        raise HttpError(exception=error)

    @staticmethod
    def set_descriptor_name(descriptor, attr_name):
        if isinstance(descriptor, descriptors.Descriptor):
            descriptor.attr_name = attr_name


class Handler(object):

    __metaclass__ = HandlerType

    SUPPORTED_HTTP_METHODS = (
        'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE',
    )

    status = '200 OK'

    headers = descriptors.Headers(
        ('Content-Type', Header('text/plain', charset='utf-8')),
    )

    cookies = descriptors.Cookies()<commit_msg>little optimization of variable usage<commit_after>import abc
import functools
import logging
import types
import itertools

from marnadi import descriptors, Header
from marnadi.errors import HttpError


class HandlerType(abc.ABCMeta):

    logger = logging.getLogger('marnadi')

    def __new__(mcs, name, bases, attributes):
        cls = super(HandlerType, mcs).__new__(mcs, name, bases, attributes)
        for attr_name, attr_value in attributes.iteritems():
            cls.set_descriptor_name(attr_value, attr_name)
        return cls

    def __setattr__(cls, attr_name, attr_value):
        super(HandlerType, cls).__setattr__(attr_name, attr_value)
        cls.set_descriptor_name(attr_value, attr_name)

    def __call__(cls, *args, **kwargs):
        if cls.func is not None:
            return cls.func(*args, **kwargs)
        return super(HandlerType, cls).__call__(*args, **kwargs)

    def decorator(cls, func):
        method = staticmethod(func)
        attributes = dict(func=method)
        for supported_method in cls.SUPPORTED_HTTP_METHODS:
            supported_method = supported_method.lower()
            if getattr(cls, supported_method, NotImplemented) is NotImplemented:
                attributes[supported_method] = method
        return functools.update_wrapper(
            type('', (cls, ), attributes),
            func, updated=(),
        )

    @staticmethod
    def make_string(entity):
        return '' if entity is None else unicode(entity).encode('utf-8')

    def log_exception(cls, func, exclude=None):
        @functools.wraps(func)
        def _func(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as error:
                if exclude and not isinstance(error, exclude):
                    cls.logger.exception(error)
                raise
        return _func

    def handle(cls, environ, start_response, args=(), kwargs=None):
        try:
            return cls.log_exception(cls._handle, exclude=HttpError)(
                environ, start_response, args=args, kwargs=kwargs
            )
        except HttpError:
            raise
        except Exception as error:
            cls.handle_exception(error, environ, args, kwargs)

    def _handle(cls, environ, start_response, args=(), kwargs=None):
        handler = super(HandlerType, cls).__call__(environ)
        result = handler(*args, **kwargs or {})
        if isinstance(result, types.GeneratorType):
            func = cls.log_exception(cls.make_string)
            chunks = itertools.imap(func, result)
        else:
            chunks = (cls.make_string(result), )
        status = handler.status
        headers = list(handler.headers.flush())
        start_response(status, headers)
        return chunks

    def handle_exception(cls, error, environ, args, kwargs):
        raise HttpError(exception=error)

    @staticmethod
    def set_descriptor_name(descriptor, attr_name):
        if isinstance(descriptor, descriptors.Descriptor):
            descriptor.attr_name = attr_name


class Handler(object):

    __metaclass__ = HandlerType

    SUPPORTED_HTTP_METHODS = (
        'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE',
    )

    status = '200 OK'

    headers = descriptors.Headers(
        ('Content-Type', Header('text/plain', charset='utf-8')),
    )

    cookies = descriptors.Cookies()
{'fraction_non_alphanumeric': 0.10209192692987626, 'fraction_numerical': 0.0014731879787860931, 'mean_word_length': 2.5958686440677967, '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': '722043', 'n_tokens_mistral': 1904, 'n_tokens_neox': 1881, 'n_words': 461}