<commit_before>"""WSGI App Creator

This module is responsible for creating the basic Pylons WSGI application. It's generally
assumed that it will be called by Paste, though any WSGI application server could create
and call the WSGI app as well.

"""
import sys

import paste.wsgiwrappers
from paste.registry import RegistryManager
from paste.wsgiwrappers import WSGIRequest
from paste.wsgiwrappers import WSGIResponse as Response

from routes import request_config
import myghty.escapes as escapes

import pylons
import pylons.templating
from pylons.util import RequestLocal
from pylons.helpers import Myghty_Compat, redirect_to

class PylonsBaseWSGIApp(object):
    """Basic Pylons WSGI Application

    This basic WSGI app is provided should a web developer want to
    get access to the most basic Pylons web application environment
    available. By itself, this Pylons web application does little more
    than dispatch to a controller and setup the context object, the
    request object, and the globals object.
    
    Additional functionality like sessions, and caching can be setup by
    altering the ``environ['pylons.environ_config']`` setting to indicate
    what key the ``session`` and ``cache`` functionality should come from.
    
    Resolving the URL and dispatching can be customized by sub-classing or
    "monkey-patching" this class. Subclassing is the preferred approach.
    
    """
    def __init__(self, mapper, package_name, globals, default_charset='UTF-8'):
        self.mapper = mapper
        self.globals = globals
        self.package_name = package_name
        self.default_charset = default_charset
        self.settings = dict(charset=default_charset, content_type='text/html')
        self.c = RequestLocal()
        config = globals.pylons_config
        self.buffet = pylons.templating.Buffet(config.templating, 
            template_root=config.template_root, **config.template_options)
    
    def __call__(self, environ, start_response):
        self.setup_app_env(environ, start_response)
        if environ.get('paste.testing'):
            self.load_test_env(environ)
        
        controller = self.resolve(environ, start_response)
        response = self.dispatch(controller, environ, start_response)
        
        # Transform HttpResponse objects into WSGI response
        if hasattr(response, 'wsgi_response'):
            status, response_headers, content = response.wsgi_response()
            start_response(status, response_headers)
            return content
        elif response:
            return response
        else:
            # Apparently we returned absolutely nothing, use the response
            # object if in legacy mode, otherwise raise an exception
            if environ.get('pylons.legacy'):
                resp = pylons.helpers.response
                if hasattr(pylons.helpers.response, 'wsgicall'):
                    # Legacy app using run_wsgi
                    return resp.content
                status, response_headers, content = resp.wsgi_response()
                start_response(status, response_headers)
                return content
            else:
                raise Exception, "No content returned by controller: %s" % controller.__name__
    
    def setup_app_env(self, environ, start_response):
        """Setup and register all the Pylons objects with the registry"""
        req = WSGIRequest(environ)
        environ['paste.registry'].register(paste.wsgiwrappers.settings, self.settings)
        environ['paste.registry'].register(pylons.request, req)
        environ['paste.registry'].register(pylons.c, self.c)
        environ['paste.registry'].register(pylons.g, self.globals)
        environ['paste.registry'].register(pylons.params, req.params)
        environ['paste.registry'].register(pylons.buffet, self.buffet)
        pylons.h()
        self.c._clear()
        
        # Setup legacy globals
        if environ.get('pylons.legacy'):
            environ['paste.registry'].register(pylons.helpers.response, Response())
            environ['paste.registry'].register(pylons.m, Myghty_Compat(environ, start_response))
        
        econf = environ['pylons.environ_config']
        if econf.get('session'):
            environ['paste.registry'].register(pylons.session, environ[econf['session']])
        if econf.get('cache'):
            environ['paste.registry'].register(pylons.cache, environ[econf['cache']])
    
    def resolve(self, environ, start_response):
        """Implements Routes-based dispatching"""
        config = request_config()
        config.mapper = self.mapper
        config.environ = environ
        config.redirect = redirect_to
        match = config.mapper_dict
        environ['pylons.routes_dict'] = match
        controller = match.get('controller')
        if not controller:
            return None
        
        # Pull the controllers class name, import controller
        # @@ TODO: Encapsulate in try/except to raise error if controller
        #          doesn't exist, or class in controller file doesn't exist.
        controller_name = self.package_name + '.controllers.' \
            + controller.lower().replace('/', '.')
        __import__(controller_name)
        controller_class = controller.split('/')[-1].title().replace('-', '_')
        classname = controller_class + 'Controller'
        controller = getattr(sys.modules[controller_name], classname)
        return controller
        
    def dispatch(self, controller, environ, start_response):
        """Dispatches to a controller, will instantiate the controller
        if necessary"""
        if not controller:
            res = Response()
            response.status_code = 404
            return response
        match = environ['pylons.routes_dict']
        if not getattr(controller, 'wsgi_application', False):
            # Sanitaze keys
            # @@ TODO: This should be done in a lazy fashion
            for k,v in match.iteritems():<commit_msg>[svn] Fixed resolution to properly deal with matches that result in nothing.<commit_after>"""WSGI App Creator

This module is responsible for creating the basic Pylons WSGI application. It's generally
assumed that it will be called by Paste, though any WSGI application server could create
and call the WSGI app as well.

"""
import sys

import paste.wsgiwrappers
from paste.registry import RegistryManager
from paste.wsgiwrappers import WSGIRequest
from paste.wsgiwrappers import WSGIResponse as Response

from routes import request_config
import myghty.escapes as escapes

import pylons
import pylons.templating
from pylons.util import RequestLocal
from pylons.helpers import Myghty_Compat, redirect_to

class PylonsBaseWSGIApp(object):
    """Basic Pylons WSGI Application

    This basic WSGI app is provided should a web developer want to
    get access to the most basic Pylons web application environment
    available. By itself, this Pylons web application does little more
    than dispatch to a controller and setup the context object, the
    request object, and the globals object.
    
    Additional functionality like sessions, and caching can be setup by
    altering the ``environ['pylons.environ_config']`` setting to indicate
    what key the ``session`` and ``cache`` functionality should come from.
    
    Resolving the URL and dispatching can be customized by sub-classing or
    "monkey-patching" this class. Subclassing is the preferred approach.
    
    """
    def __init__(self, mapper, package_name, globals, default_charset='UTF-8'):
        self.mapper = mapper
        self.globals = globals
        self.package_name = package_name
        self.default_charset = default_charset
        self.settings = dict(charset=default_charset, content_type='text/html')
        self.c = RequestLocal()
        config = globals.pylons_config
        self.buffet = pylons.templating.Buffet(config.templating, 
            template_root=config.template_root, **config.template_options)
    
    def __call__(self, environ, start_response):
        self.setup_app_env(environ, start_response)
        if environ.get('paste.testing'):
            self.load_test_env(environ)
        
        controller = self.resolve(environ, start_response)
        response = self.dispatch(controller, environ, start_response)
        
        # Transform HttpResponse objects into WSGI response
        if hasattr(response, 'wsgi_response'):
            status, response_headers, content = response.wsgi_response()
            start_response(status, response_headers)
            return content
        elif response:
            return response
        else:
            # Apparently we returned absolutely nothing, use the response
            # object if in legacy mode, otherwise raise an exception
            if environ.get('pylons.legacy'):
                resp = pylons.helpers.response
                if hasattr(pylons.helpers.response, 'wsgicall'):
                    # Legacy app using run_wsgi
                    return resp.content
                status, response_headers, content = resp.wsgi_response()
                start_response(status, response_headers)
                return content
            else:
                raise Exception, "No content returned by controller: %s" % controller.__name__
    
    def setup_app_env(self, environ, start_response):
        """Setup and register all the Pylons objects with the registry"""
        req = WSGIRequest(environ)
        environ['paste.registry'].register(paste.wsgiwrappers.settings, self.settings)
        environ['paste.registry'].register(pylons.request, req)
        environ['paste.registry'].register(pylons.c, self.c)
        environ['paste.registry'].register(pylons.g, self.globals)
        environ['paste.registry'].register(pylons.params, req.params)
        environ['paste.registry'].register(pylons.buffet, self.buffet)
        pylons.h()
        self.c._clear()
        
        # Setup legacy globals
        if environ.get('pylons.legacy'):
            environ['paste.registry'].register(pylons.helpers.response, Response())
            environ['paste.registry'].register(pylons.m, Myghty_Compat(environ, start_response))
        
        econf = environ['pylons.environ_config']
        if econf.get('session'):
            environ['paste.registry'].register(pylons.session, environ[econf['session']])
        if econf.get('cache'):
            environ['paste.registry'].register(pylons.cache, environ[econf['cache']])
    
    def resolve(self, environ, start_response):
        """Implements Routes-based dispatching"""
        config = request_config()
        config.mapper = self.mapper
        config.environ = environ
        config.redirect = redirect_to
        match = config.mapper_dict
        if not match:
            return None
        environ['pylons.routes_dict'] = match
        controller = match.get('controller')
        if not controller:
            return None
        
        # Pull the controllers class name, import controller
        # @@ TODO: Encapsulate in try/except to raise error if controller
        #          doesn't exist, or class in controller file doesn't exist.
        controller_name = self.package_name + '.controllers.' \
            + controller.lower().replace('/', '.')
        __import__(controller_name)
        controller_class = controller.split('/')[-1].title().replace('-', '_')
        classname = controller_class + 'Controller'
        controller = getattr(sys.modules[controller_name], classname)
        return controller
        
    def dispatch(self, controller, environ, start_response):
        """Dispatches to a controller, will instantiate the controller
        if necessary"""
        if not controller:
            res = Response()
            res.status_code = 404
            return res
        match = environ['pylons.routes_dict']
        if not getattr(controller, 'wsgi_application', False):
            # Sanitaze keys
            # @@ TODO: This should be done in a lazy fashion
            for k,v in match.iteritems():
{'fraction_non_alphanumeric': 0.08590071859254976, 'fraction_numerical': 0.0008259684480052862, 'mean_word_length': 2.6892138939670933, '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': '575425', 'n_tokens_mistral': 3216, 'n_tokens_neox': 3169, 'n_words': 915}