Latest Version: 0.9.6.2
/Users/bbangert/Programming/Python/pylons/pylons/util.py
0001"""Paste Template and Pylons utility functions
0002
0003PylonsTemplate is a Paste Template sub-class that configures the source
0004directory and default plug-ins for a new Pylons project. The minimal template
0005provides a more minimal template with less additional directories and layout.
0006"""
0007import logging
0008import warnings
0009
0010from paste.script.appinstall import Installer
0011from paste.script.templates import Template
0012
0013import pylons
0014import pylons.configuration
0015import pylons.i18n
0016
0017__all__ = ['AttribSafeContextObj', 'ContextObj', 'Helpers',
0018           'class_name_from_module_name', 'log', '_', 'set_lang', 'get_lang']
0019__pudge_all__ = __all__ + ['MinimalPylonsTemplate', 'PylonsTemplate']
0020
0021pylons_log = logging.getLogger(__name__)
0022
0023def func_move(name, moved_to='pylons.i18n'):
0024    return ("The %s function has moved to %s, please update your import "
0025            "statements to reflect the move" % (name, moved_to))
0026
0027
0028def deprecated(func, message):
0029    def deprecated_method(*args, **kargs):
0030        warnings.warn(message, DeprecationWarning, 2)
0031        return func(*args, **kargs)
0032    try:
0033        deprecated_method.__name__ = func.__name__
0034    except TypeError: # Python < 2.4
0035        pass
0036    deprecated_method.__doc__ = message + "\n\n" + func.__doc__
0037    return deprecated_method
0038
0039
0040get_lang = deprecated(pylons.i18n.get_lang, func_move('get_lang'))
0041set_lang = deprecated(pylons.i18n.set_lang, func_move('set_lang'))
0042_ = deprecated(pylons.i18n._, func_move('_'))
0043
0044# Avoid circular import and a double warning
0045def log(*args, **kwargs):
0046    """Deprecated: Use the logging module instead.
0047
0048    Log a message to the output log.
0049    """
0050    import pylons.helpers
0051    return pylons.helpers.log(*args, **kwargs)
0052
0053def get_prefix(environ, warn=True):
0054    """Deprecated: Use environ.get('SCRIPT_NAME', '') instead"""
0055    if warn:
0056        warnings.warn("The get_prefix function is deprecated, please use "
0057                      "environ.get('SCRIPT_NAME', '') instead",
0058                      DeprecationWarning, 2)
0059    prefix = pylons.config.get('prefix', '')
0060    if not prefix:
0061        if environ.get('SCRIPT_NAME', '') != '':
0062            prefix = environ['SCRIPT_NAME']
0063    return prefix
0064
0065
0066def class_name_from_module_name(module_name):
0067    """Takes a module name and returns the name of the class it defines.
0068
0069    If the module name contains dashes, they are replaced with underscores.
0070
0071    Example::
0072
0073        >>> class_name_from_module_name('with-dashes')
0074        'WithDashes'
0075        >>> class_name_from_module_name('with_underscores')
0076        'WithUnderscores'
0077        >>> class_name_from_module_name('oneword')
0078        'Oneword'
0079    """
0080    words = module_name.replace('-', '_').split('_')
0081    return ''.join([w.title() for w in words])
0082
0083
0084class ContextObj(object):
0085    """The 'c' object, with strict attribute access (raises an Exception when
0086    the attribute does not exist)"""
0087    def __repr__(self):
0088        attrs = [(name, value)
0089                 for name, value in self.__dict__.items()
0090                 if not name.startswith('_')]
0091        attrs.sort()
0092        parts = []
0093        for name, value in attrs:
0094            value_repr = repr(value)
0095            if len(value_repr) > 70:
0096                value_repr = value_repr[:60] + '...' + value_repr[-5:]
0097            parts.append(' %s=%s' % (name, value_repr))
0098        return '<%s.%s at %s%s>' % (
0099            self.__class__.__module__,
0100            self.__class__.__name__,
0101            hex(id(self)),
0102            ','.join(parts))
0103
0104
0105class AttribSafeContextObj(ContextObj):
0106    """The 'c' object, with lax attribute access (returns '' when the attribute
0107    does not exist)"""
0108    def __getattr__(self, name):
0109        try:
0110            return object.__getattribute__(self, name)
0111        except AttributeError:
0112            pylons_log.debug("No attribute called %s found on c object, "
0113                             "returning empty string", name)
0114            return ''
0115
0116
0117class PylonsTemplate(Template):
0118    _template_dir = 'templates/default_project'
0119    summary = 'Pylons application template'
0120    egg_plugins = ['Pylons', 'WebHelpers']
0121
0122    def pre(self, command, output_dir, vars):
0123        """Called before template is applied."""
0124        package_logger = vars['package']
0125        if package_logger == 'root':
0126            # Rename the app logger in the rare case a project is named 'root'
0127            package_logger = 'app'
0128        vars['package_logger'] = package_logger
0129
0130        template_engine =               vars.setdefault('template_engine',
0132                            pylons.configuration.default_template_engine)
0133
0134        if template_engine == 'mako':
0135            # Support a Babel extractor default for Mako
0136            vars['babel_templates_extractor'] =                   "('templates/**.mako', 'mako', None),\n%s#%s" % (' ' * 4,
0138                                                                 ' ' * 8)
0139        else:
0140            vars['babel_templates_extractor'] = ''
0141
0142class MinimalPylonsTemplate(PylonsTemplate):
0143    _template_dir = 'templates/minimal_project'
0144    summary = 'Pylons minimal application template'
0145
0146
0147class PylonsInstaller(Installer):
0148    use_cheetah = False

Top