<commit_before># -*- coding: utf-8 -*-
"""
This module defines the class for decorating controller methods so that on
call the methods can be expressed using expose, validate, and other
decorators to effect a rendered page.
"""

from urllib import url2pathname
import inspect
import formencode
import tg
from tg.controllers.util import abort

try:
    from repoze.what.predicates import NotAuthorizedError as WhatNotAuthorizedError, not_anonymous
except ImportError:
    class WhatNotAuthorizedError(Exception): pass
    def not_anonymous(): pass

# demand load tw (ToscaWidets) if needed
tw = None

from tg.render import render as tg_render
from tg.decorators import expose
from tg.flash import flash
from tg.jsonify import is_saobject, JsonEncodeError

from util import pylons_formencode_gettext

class NotAuthorizedError(Exception): pass

class DecoratedController(object):
    """Creates an interface to hang decoration attributes on
    controller methods for the purpose of rendering web content.
    """
    
    def _is_exposed(self, controller, name):
        method = getattr(controller, name, None)
        if method and inspect.ismethod(method) and hasattr(method, 'decoration'):
            return method.decoration.exposed

    def _call(self, tgl, controller, params, remainder=None):
        """
        _call is called by _perform_call in Pylons' WSGIController.

        Any of the before_validate hook, the validation, the before_call hook,
        and the controller method can return a FormEncode Invalid exception,
        which will give the validation error handler the opportunity to provide
        a replacement decorated controller method and output that will
        subsequently be rendered.

        This allows for validation to display the original page or an
        abbreviated form with validation errors shown on validation failure.

        The before_render hook provides a place for functions that are called
        before the template is rendered. For example, you could use it to
        add and remove from the dictionary returned by the controller method,
        before it is passed to rendering.

        The after_render hook can act upon and modify the response out of
        rendering.

        """
        self._initialize_validation_context(tgl)

        #This is necessary to prevent spurious Content Type header which would
        #cause problems to paste.response.replace_header calls and cause
        #responses wihout content type to get out with a wrong content type
        resp_headers = tgl.response.headers
        if not resp_headers.get('Content-Type'):
            resp_headers.pop('Content-Type', None)

        remainder = remainder or []
        remainder = [url2pathname(r) for r in remainder]

        tg_decoration = controller.decoration
        try:
            tg_decoration.run_hooks(tgl, 'before_validate', remainder, params)

            validate_params = self._get_params_with_argspec(controller, params, remainder)

            # Validate user input
            params = self._perform_validate(controller, validate_params)

            tgl.tmpl_context.form_values = params

            tg_decoration.run_hooks(tgl, 'before_call', remainder, params)

            params, remainder = self._remove_argspec_params_from_params(controller, params, remainder)

            #apply controller wrappers
            controller_callable = tg_decoration.wrap_controller(tgl, controller)

            # call controller method
            output = controller_callable(*remainder, **params)

        except formencode.api.Invalid, inv:
            controller, output = self._handle_validation_errors(controller,
                                                                remainder,
                                                                params, inv)
        except Exception, e:
            if tgl.config.get('use_toscawidgets2'):
                from tw2.core import ValidationError
                if isinstance(e, ValidationError):
                    controller, output = self._handle_validation_errors(controller,
                                                                remainder,
                                                                params, e)
                else:
                    raise
            else:
                raise


        # Render template
        tg_decoration.run_hooks(tgl, 'before_render', remainder, params, output)

        response = self._render_response(tgl, controller, output)
        
        tg_decoration.run_hooks(tgl, 'after_render', response)
        
        return response['response']


    def _perform_validate(self, controller, params):
        """
        Validation is stored on the "validation" attribute of the controller's<commit_msg>Be sure that we update decoration when controller has been changed due to validation errors<commit_after># -*- coding: utf-8 -*-
"""
This module defines the class for decorating controller methods so that on
call the methods can be expressed using expose, validate, and other
decorators to effect a rendered page.
"""

from urllib import url2pathname
import inspect
import formencode
import tg
from tg.controllers.util import abort

try:
    from repoze.what.predicates import NotAuthorizedError as WhatNotAuthorizedError, not_anonymous
except ImportError:
    class WhatNotAuthorizedError(Exception): pass
    def not_anonymous(): pass

# demand load tw (ToscaWidets) if needed
tw = None

from tg.render import render as tg_render
from tg.decorators import expose
from tg.flash import flash
from tg.jsonify import is_saobject, JsonEncodeError

from util import pylons_formencode_gettext

class NotAuthorizedError(Exception): pass

class DecoratedController(object):
    """Creates an interface to hang decoration attributes on
    controller methods for the purpose of rendering web content.
    """
    
    def _is_exposed(self, controller, name):
        method = getattr(controller, name, None)
        if method and inspect.ismethod(method) and hasattr(method, 'decoration'):
            return method.decoration.exposed

    def _call(self, tgl, controller, params, remainder=None):
        """
        _call is called by _perform_call in Pylons' WSGIController.

        Any of the before_validate hook, the validation, the before_call hook,
        and the controller method can return a FormEncode Invalid exception,
        which will give the validation error handler the opportunity to provide
        a replacement decorated controller method and output that will
        subsequently be rendered.

        This allows for validation to display the original page or an
        abbreviated form with validation errors shown on validation failure.

        The before_render hook provides a place for functions that are called
        before the template is rendered. For example, you could use it to
        add and remove from the dictionary returned by the controller method,
        before it is passed to rendering.

        The after_render hook can act upon and modify the response out of
        rendering.

        """
        self._initialize_validation_context(tgl)

        #This is necessary to prevent spurious Content Type header which would
        #cause problems to paste.response.replace_header calls and cause
        #responses wihout content type to get out with a wrong content type
        resp_headers = tgl.response.headers
        if not resp_headers.get('Content-Type'):
            resp_headers.pop('Content-Type', None)

        remainder = remainder or []
        remainder = [url2pathname(r) for r in remainder]

        tg_decoration = controller.decoration
        try:
            tg_decoration.run_hooks(tgl, 'before_validate', remainder, params)

            validate_params = self._get_params_with_argspec(controller, params, remainder)

            # Validate user input
            params = self._perform_validate(controller, validate_params)

            tgl.tmpl_context.form_values = params

            tg_decoration.run_hooks(tgl, 'before_call', remainder, params)

            params, remainder = self._remove_argspec_params_from_params(controller, params, remainder)

            #apply controller wrappers
            controller_callable = tg_decoration.wrap_controller(tgl, controller)

            # call controller method
            output = controller_callable(*remainder, **params)

        except formencode.api.Invalid, inv:
            controller, output = self._handle_validation_errors(controller,
                                                                remainder,
                                                                params, inv)
        except Exception, e:
            if tgl.config.get('use_toscawidgets2'):
                from tw2.core import ValidationError
                if isinstance(e, ValidationError):
                    controller, output = self._handle_validation_errors(controller,
                                                                remainder,
                                                                params, e)
                else:
                    raise
            else:
                raise


        #Be sure that we run hooks if the controller changed due to validation errors
        tg_decoration = controller.decoration

        # Render template
        tg_decoration.run_hooks(tgl, 'before_render', remainder, params, output)

        response = self._render_response(tgl, controller, output)
        
        tg_decoration.run_hooks(tgl, 'after_render', response)
        
        return response['response']


    def _perform_validate(self, controller, params):
        """
        Validation is stored on the "validation" attribute of the controller's
{'fraction_non_alphanumeric': 0.05466435066925513, 'fraction_numerical': 0.0010217635639113108, 'mean_word_length': 2.3751724137931034, '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': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3853655', 'n_tokens_mistral': 2328, 'n_tokens_neox': 2242, 'n_words': 849}