This file is indexed.

/usr/lib/python2.7/dist-packages/pylons/util.py is in python-pylons 1.0.2-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""Paste Template and Pylons utility functions

PylonsTemplate is a Paste Template sub-class that configures the source
directory and default plug-ins for a new Pylons project. The minimal
template a more minimal template with less additional directories and
layout.

"""
import logging
import sys

import pkg_resources
from paste.deploy.converters import asbool
from paste.script.appinstall import Installer
from paste.script.templates import Template, var
from tempita import paste_script_template_renderer

import pylons
import pylons.configuration
import pylons.i18n

__all__ = ['AttribSafeContextObj', 'ContextObj', 'PylonsContext',
           'class_name_from_module_name', 'call_wsgi_application']

log = logging.getLogger(__name__)


def call_wsgi_application(application, environ, catch_exc_info=False):
    """
    Call the given WSGI application, returning ``(status_string,
    headerlist, app_iter)``

    Be sure to call ``app_iter.close()`` if it's there.

    If catch_exc_info is true, then returns ``(status_string,
    headerlist, app_iter, exc_info)``, where the fourth item may
    be None, but won't be if there was an exception.  If you don't
    do this and there was an exception, the exception will be
    raised directly.

    """
    captured = []
    output = []

    def start_response(status, headers, exc_info=None):
        if exc_info is not None and not catch_exc_info:
            raise exc_info[0], exc_info[1], exc_info[2]
        captured[:] = [status, headers, exc_info]
        return output.append
    app_iter = application(environ, start_response)
    if not captured or output:
        try:
            output.extend(app_iter)
        finally:
            if hasattr(app_iter, 'close'):
                app_iter.close()
        app_iter = output
    if catch_exc_info:
        return (captured[0], captured[1], app_iter, captured[2])
    else:
        return (captured[0], captured[1], app_iter)


def class_name_from_module_name(module_name):
    """Takes a module name and returns the name of the class it
    defines.

    If the module name contains dashes, they are replaced with
    underscores.

    Example::

        >>> class_name_from_module_name('with-dashes')
        'WithDashes'
        >>> class_name_from_module_name('with_underscores')
        'WithUnderscores'
        >>> class_name_from_module_name('oneword')
        'Oneword'

    """
    words = module_name.replace('-', '_').split('_')
    return ''.join(w.title() for w in words)


class PylonsContext(object):
    """Pylons context object

    All the Pylons Stacked Object Proxies are also stored here, for use
    in generators and async based operation where the globals can't be
    used.

    This object is attached in
    :class:`~pylons.controllers.core.WSGIController` instances as
    :attr:`~WSGIController._py_object`. For example::

        class MyController(WSGIController):
            def index(self):
                pyobj = self._py_object
                return "Environ is %s" % pyobj.request.environ

    """
    pass


class ContextObj(object):
    """The :term:`tmpl_context` object, with strict attribute access
    (raises an Exception when the attribute does not exist)"""
    def __repr__(self):
        attrs = sorted((name, value)
                       for name, value in self.__dict__.iteritems()
                       if not name.startswith('_'))
        parts = []
        for name, value in attrs:
            value_repr = repr(value)
            if len(value_repr) > 70:
                value_repr = value_repr[:60] + '...' + value_repr[-5:]
            parts.append(' %s=%s' % (name, value_repr))
        return '<%s.%s at %s%s>' % (
            self.__class__.__module__,
            self.__class__.__name__,
            hex(id(self)),
            ','.join(parts))


class AttribSafeContextObj(ContextObj):
    """The :term:`tmpl_context` object, with lax attribute access (
    returns '' when the attribute does not exist)"""
    def __getattr__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            log.debug("No attribute called %s found on c object, returning "
                      "empty string", name)
            return ''


class PylonsTemplate(Template):
    _template_dir = ('pylons', 'templates/default_project')
    template_renderer = staticmethod(paste_script_template_renderer)
    summary = 'Pylons application template'
    egg_plugins = ['PasteScript', 'Pylons']
    vars = [
        var('template_engine', 'mako/genshi/jinja2/etc: Template language',
            default='mako'),
        var('sqlalchemy', 'True/False: Include SQLAlchemy configuration',
            default=False),
    ]
    ensure_names = ['description', 'author', 'author_email', 'url']

    def pre(self, command, output_dir, vars):
        """Called before template is applied."""
        package_logger = vars['package']
        if package_logger == 'root':
            # Rename the app logger in the rare case a project is named 'root'
            package_logger = 'app'
        vars['package_logger'] = package_logger
        vars['template_engine'] = 'mako'

        template_engine = 'mako'

        if template_engine == 'mako':
            # Support a Babel extractor default for Mako
            vars['babel_templates_extractor'] = \
                ("('templates/**.mako', 'mako', {'input_encoding': 'utf-8'})"
                 ",\n%s#%s" % (' ' * 4, ' ' * 8))
        else:
            vars['babel_templates_extractor'] = ''

        # Ensure these exist in the namespace
        for name in self.ensure_names:
            vars.setdefault(name, '')

        vars['version'] = vars.get('version', '0.1')
        vars['zip_safe'] = asbool(vars.get('zip_safe', 'false'))
        vars['sqlalchemy'] = asbool(vars.get('sqlalchemy', 'false'))


class MinimalPylonsTemplate(PylonsTemplate):
    _template_dir = ('pylons', 'templates/minimal_project')
    summary = 'Pylons minimal application template'
    vars = [
        var('template_engine', 'mako/genshi/jinja2/etc: Template language',
            default='mako'),
    ]


class LegacyPylonsTemplate(PylonsTemplate):
    _template_dir = ('pylons', 'templates/legacy_project')
    summary = 'Pylons legacy application template'
    vars = [
        var('template_engine', 'mako/genshi/jinja2/etc: Template language',
            default='mako'),
    ]


class NewPylonsTemplate(PylonsTemplate):
    _template_dir = ('pylons', 'templates/new_project')
    summary = 'Pylons "newstyle" application template'
    vars = []


class NewMinimalPylonsTemplate(PylonsTemplate):
    _template_dir = ('pylons', 'templates/newminimal_project')
    summary = 'Pylons "newstyle" minimal application template'
    vars = []


class NewSQLAlchemyTemplate(PylonsTemplate):
    _template_dir = ('pylons', 'templates/newsqla_project')
    summary = 'Pylons "newstyle" SQLAlchemy template'
    vars = []


class PylonsInstaller(Installer):
    use_cheetah = False
    config_file = 'config/deployment.ini_tmpl'

    def config_content(self, command, vars):
        """
        Called by ``self.write_config``, this returns the text content
        for the config file, given the provided variables.
        """
        modules = [line.strip()
                    for line in self.dist.get_metadata_lines('top_level.txt')
                    if line.strip() and not line.strip().startswith('#')]
        if not modules:
            print >> sys.stderr, 'No modules are listed in top_level.txt'
            print >> sys.stderr, \
                'Try running python setup.py egg_info to regenerate that file'
        for module in modules:
            if pkg_resources.resource_exists(module, self.config_file):
                return self.template_renderer(
                    pkg_resources.resource_string(module, self.config_file),
                    vars, filename=self.config_file)
        # Legacy support for the old location in egg-info
        return super(PylonsInstaller, self).config_content(command, vars)


def resolve_dotted(name):
    return pkg_resources.EntryPoint.parse('x=%s' % name).load(False)