Warning
This documentation does not refer to the most recent version of Pylons. Current Documentation
0001"""Configuration setup for Myghty, and Paste error middleware
0002
0003This module supplies pylons_config which handles setting up defaults
0004for Myghty, Paste errorware, and prefixing Routes if necessary.
0005"""
0006import os
0007from myghty.resolver import *
0008from paste.deploy.converters import asbool
0009
0010class Config(object):
0011 """Pylons configuration object
0012
0013 The Pylons configuration object is a per-application instance object
0014 that retains the information regarding the global and app conf's as
0015 well as per-application instance specific data such as the mapper, the
0016 paths for this instance, and the myghty configuration.
0017
0018 The Config object is available in your application as a Pylons global
0019 ``pylons_config`` under the ``g`` object. There's several useful
0020 attributes of the config object most people will be interested in:
0021
0022 ``myghty``
0023 The myghty configuration dict that was used to initialize Myghty
0024 ``map``
0025 Mapper object used for Routing. Yes, it is possible to add routes
0026 after your application has started running.
0027 ``paths``
0028 An array of absolute paths that were defined in the applications
0029 ``config/environment.py`` module.
0030 ``global_conf``
0031 Global configuration passed in from Paste, this corresponds to the
0032 DEFAULTS section in the config file.
0033 ``app_conf``
0034 Application specific configuration directives, passed in via Paste
0035 from the app section of the config file.
0036 ``environ_config``
0037 Dict of environ keys for where in the environ to pickup various
0038 objects for registering with Pylons. If these are present then
0039 PylonsApp will use them from environ rather than using default
0040 middleware from Beaker. Valid keys are: ``session, cache``
0041 ``template_engines``
0042 List of template engines to configure. The first one in the list will
0043 be configured as the default template engine. Each item in the list is
0044 a dict indicating how to configure the template engine with keys:
0045 ``engine``, ``template_root``, ``template_options``, and ``alias``
0046
0047 """
0048 def __init__(self, myghty, map, paths, environ_config=None):
0049 if environ_config is None:
0050 environ_config = {}
0051 self.myghty = myghty
0052 self.map = map
0053 self.paths = paths
0054 self.global_conf = {}
0055 self.app_conf = {}
0056 self.template_engines = []
0057 self.environ_config = environ_config
0058
0059 def add_template_engine(self, engine, root, options, alias=None):
0060 """Add additional template engines for configuration on Pylons WSGI init
0061
0062 ``engine``
0063 The name of the template engine
0064
0065 ``root``
0066 Template root for the engine
0067
0068 ``options``
0069 Dict of additional options used during engine initialization
0070
0071 ``alias``
0072 Name engine should respond to when actually used. This allows for
0073 multiple configurations of the same engine and lets you alias the
0074 additional ones to other names.
0075
0076 Example of Kid addition::
0077
0078 # In yourproj/middleware.py
0079 # ...
0080 config.init_app(global_conf, app_conf, package='yourproj')
0081
0082 # Load additional template engines
0083 kidopts = {'kid.assume_encoding':'utf-8', 'kid.encoding':'utf-8'}
0084 config.add_template_engine('kid', 'yourproj.kidtemplates', kidopts)
0085
0086 Example of changing the default template engine::
0087
0088 # In yourproj/middleware.py
0089 # ...
0090 config.init_app(global_conf, app_conf, package='yourproj')
0091
0092 # Remove existing template engine
0093 old_default = config.template_engines.pop()
0094
0095 # Load additional template engines
0096 kidopts = {'kid.assume_encoding':'utf-8', 'kid.encoding':'utf-8'}
0097 config.add_template_engine('kid', 'yourproj.kidtemplates', kidopts)
0098
0099 # Add old default as additional engine
0100 config.template_engines.append(old_default)
0101
0102 """
0103 config = dict(engine=engine, template_root=root, template_options=options, alias=alias)
0104 self.template_engines.append(config)
0105
0106 def init_app(self, global_conf, app_conf, package):
0107 """Initialize configuration for the application
0108
0109 ``global_config``
0110 Several options are expected to be set for a Pylons web application.
0111 They will be loaded from the global_config which has the main Paste
0112 options. If ``debug`` is not enabled as a global config option, the
0113 following option *must* be set:
0114
0115 * error_to - The email address to send the debug error to
0116
0117 The optional config options in this case are:
0118
0119 * smtp_server - The SMTP server to use, defaults to 'localhost'
0120 * error_log - A logfile to write the error to
0121 * error_subject_prefix - The prefix of the error email subject
0122 * from_address - Whom the error email should be from
0123 ``app_conf``
0124 Defaults supplied via the [app:main] section from the Paste
0125 config file. ``load_config`` only cares about whether a 'prefix'
0126 option is set, if so it will update Routes to ensure URL's take
0127 that into account.
0128 ``package``
0129 The name of the application package, to be stored in the app_conf.
0130
0131 """
0132 self.global_conf = global_conf
0133 self.app_conf = app_conf
0134 self.package = package
0135
0136 app_conf['package'] = package
0137
0138 # Setup the prefix to override the routes if necessary.
0139 prefix = app_conf.get('prefix')
0140 if not prefix:
0141 prefix = global_conf.get('prefix')
0142 if prefix:
0143 self.map.prefix = app_conf['prefix']
0144 self.map._created_regs = False
0145
0146 myghty_defaults = {}
0147
0148 # Raise a complete error for the error middleware to catch
0149 myghty_defaults['raise_error'] = True
0150
0151 # Standard Pylons configuration directives for Myghty
0152 myghty_defaults.setdefault('allow_globals', [])
0153
0154 myghty_defaults['allow_globals'].extend(
0155 ['c', 'h', 's', 'session', 'request', 'params', 'g', 'render', 'render_fragment']
0156 )
0157 myghty_defaults['component_root'] = [{os.path.basename(path): path} for path in self.paths['templates']]
0159
0160 errorware = {}
0161 # Load the errorware configuration from the Paste configuration file
0162 # These all have defaults, and emails are only sent if configured and
0163 # if this application is running in production mode
0164 errorware['debug'] = asbool(global_conf.get('debug'))
0165 if not errorware['debug']:
0166 errorware['debug'] = False
0167 errorware['error_email'] = global_conf.get('email_to')
0168 errorware['error_log'] = global_conf.get('error_log', None)
0169 errorware['smtp_server'] = global_conf.get('smtp_server', 'localhost')
0170 errorware['error_subject_prefix'] = global_conf.get('error_subject_prefix', 'WebApp Error: ')
0171 errorware['from_address'] = global_conf.get('from_address',
0172 global_conf.get('error_email_from', 'pylons@yourapp.com'))
0173 errorware['error_message'] = global_conf.get('error_message', 'An internal server error occurred')
0174
0175 # Merge in the user-supplied Myghty values
0176 myghty_defaults.update(self.myghty)
0177 self.myghty = myghty_defaults
0178 myghty_template_options = {}
0179 if app_conf.get('cache_dir', False):
0180 myghty_defaults['data_dir'] = app_conf['cache_dir']
0181 else:
0182 myghty_defaults['data_dir'] = app_conf['myghty_data_dir']
0183
0184 # Copy Myghty defaults and options into template options
0185 for k, v in self.myghty.iteritems():
0186 myghty_template_options['myghty.'+k] = v
0187
0188 # Legacy copy of session and cache settings into app_conf
0189 if k.startswith('session_') or k.startswith('cache_'):
0190 self.app_conf[k] = v
0191
0192 if not app_conf.has_key('session_data_dir'):
0193 app_conf['session_data_dir'] = os.path.join(app_conf['cache_dir'], 'sessions')
0194 if not app_conf.has_key('cache_data_dir'):
0195 app_conf['cache_data_dir'] = app_conf['cache_dir']
0196
0197 # Prepare our default template engine
0198 self.add_template_engine('pylonsmyghty', None, myghty_template_options)
0199
0200 # Save our errorware values
0201 self.errorware = errorware