summaryrefslogtreecommitdiff
path: root/pecan/compat
diff options
context:
space:
mode:
authorRyan Petrello <lists@ryanpetrello.com>2012-03-30 13:11:44 -0400
committerRyan Petrello <lists@ryanpetrello.com>2012-03-30 13:11:44 -0400
commitc9d2a679ac9a8fbd8ead2a354a310b2b8cee2613 (patch)
tree5424c890c65b0e81b3f1604938ea27bebe403750 /pecan/compat
parent5bd40db68c0423f8d33607fd739f41ff54b3b08f (diff)
downloadpecan-c9d2a679ac9a8fbd8ead2a354a310b2b8cee2613.tar.gz
pep8 love.
Diffstat (limited to 'pecan/compat')
-rw-r--r--pecan/compat/dictconfig.py61
1 files changed, 36 insertions, 25 deletions
diff --git a/pecan/compat/dictconfig.py b/pecan/compat/dictconfig.py
index 30ee64f..d077d00 100644
--- a/pecan/compat/dictconfig.py
+++ b/pecan/compat/dictconfig.py
@@ -21,6 +21,7 @@ import types
IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
+
def valid_ident(s):
m = IDENTIFIER.match(s)
if not m:
@@ -33,7 +34,7 @@ def valid_ident(s):
try:
from logging import _checkLevel
except ImportError:
- def _checkLevel(level):
+ def _checkLevel(level): # noqa
if isinstance(level, int):
rv = level
elif str(level) == level:
@@ -54,6 +55,7 @@ except ImportError:
# Each wrapper should have a configurator attribute holding the actual
# configurator to use for conversion.
+
class ConvertingDict(dict):
"""A converting dictionary wrapper."""
@@ -68,7 +70,7 @@ class ConvertingDict(dict):
result.parent = self
result.key = key
return result
-
+
def get(self, key, default=None):
value = dict.get(self, key, default)
result = self.configurator.convert(value)
@@ -80,7 +82,7 @@ class ConvertingDict(dict):
result.parent = self
result.key = key
return result
-
+
def pop(self, key, default=None):
value = dict.pop(self, key, default)
result = self.configurator.convert(value)
@@ -91,6 +93,7 @@ class ConvertingDict(dict):
result.key = key
return result
+
class ConvertingList(list):
"""A converting list wrapper."""
def __getitem__(self, key):
@@ -114,6 +117,7 @@ class ConvertingList(list):
result.parent = self
return result
+
class ConvertingTuple(tuple):
"""A converting tuple wrapper."""
def __getitem__(self, key):
@@ -126,11 +130,12 @@ class ConvertingTuple(tuple):
result.key = key
return result
+
class BaseConfigurator(object):
"""
The configurator base class which defines some useful defaults.
"""
-
+
CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
@@ -139,8 +144,8 @@ class BaseConfigurator(object):
DIGIT_PATTERN = re.compile(r'^\d+$')
value_converters = {
- 'ext' : 'ext_convert',
- 'cfg' : 'cfg_convert',
+ 'ext': 'ext_convert',
+ 'cfg': 'cfg_convert',
}
# We might want to use a different one, e.g. importlib
@@ -176,7 +181,7 @@ class BaseConfigurator(object):
def ext_convert(self, value):
"""Default converter for the ext:// protocol."""
return self.resolve(value)
-
+
def cfg_convert(self, value):
"""Default converter for the cfg:// protocol."""
rest = value
@@ -199,7 +204,7 @@ class BaseConfigurator(object):
d = d[idx]
else:
try:
- n = int(idx) # try as number first (most likely)
+ n = int(idx) # try as number first
d = d[n]
except TypeError:
d = d[idx]
@@ -227,7 +232,7 @@ class BaseConfigurator(object):
isinstance(value, tuple):
value = ConvertingTuple(value)
value.configurator = self
- elif isinstance(value, basestring): # str for py3k
+ elif isinstance(value, basestring): # str for py3k
m = self.CONVERT_PATTERN.match(value)
if m:
d = m.groupdict()
@@ -238,11 +243,12 @@ class BaseConfigurator(object):
converter = getattr(self, converter)
value = converter(suffix)
return value
-
+
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
- if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
+ if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and \
+ type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
@@ -259,6 +265,7 @@ class BaseConfigurator(object):
value = tuple(value)
return value
+
class DictConfigurator(BaseConfigurator):
"""
Configure logging using a dictionary-like object to describe the
@@ -285,7 +292,7 @@ class DictConfigurator(BaseConfigurator):
for name in handlers:
if name not in logging._handlers:
raise ValueError('No handler found with '
- 'name %r' % name)
+ 'name %r' % name)
else:
try:
handler = logging._handlers[name]
@@ -312,10 +319,10 @@ class DictConfigurator(BaseConfigurator):
'logger: %s' % e)
else:
disable_existing = config.pop('disable_existing_loggers', True)
-
+
logging._handlers.clear()
del logging._handlerList[:]
-
+
# Do formatters first - they don't refer to anything else
formatters = config.get('formatters', EMPTY_DICT)
for name in formatters:
@@ -347,7 +354,7 @@ class DictConfigurator(BaseConfigurator):
raise ValueError('Unable to configure handler '
'%r: %s' % (name, e))
# Next, do loggers - they refer to handlers and filters
-
+
#we don't want to lose the existing loggers,
#since other threads may have pointers to them.
#existing is set to contain all existing loggers,
@@ -374,7 +381,7 @@ class DictConfigurator(BaseConfigurator):
prefixed = name + "."
pflen = len(prefixed)
num_existing = len(existing)
- i = i + 1 # look at the entry after name
+ i = i + 1 # look at the entry after name
while (i < num_existing) and\
(existing[i][:pflen] == prefixed):
child_loggers.append(existing[i])
@@ -385,7 +392,7 @@ class DictConfigurator(BaseConfigurator):
except StandardError, e:
raise ValueError('Unable to configure logger '
'%r: %s' % (name, e))
-
+
#Disable any old loggers. There's no point deleting
#them as other threads may continue to hold references
#and by disabling them, you stop them doing any logging.
@@ -399,12 +406,12 @@ class DictConfigurator(BaseConfigurator):
logger.propagate = True
elif disable_existing:
logger.disabled = True
-
+
# And finally, do the root logger
root = config.get('root', None)
if root:
try:
- self.configure_root(root)
+ self.configure_root(root)
except StandardError, e:
raise ValueError('Unable to configure root '
'logger: %s' % e)
@@ -414,7 +421,7 @@ class DictConfigurator(BaseConfigurator):
def configure_formatter(self, config):
"""Configure a formatter from a dictionary."""
if '()' in config:
- factory = config['()'] # for use in exception handler
+ factory = config['()'] # for use in exception handler
try:
result = self.configure_custom(config)
except TypeError, te:
@@ -432,7 +439,7 @@ class DictConfigurator(BaseConfigurator):
dfmt = config.get('datefmt', None)
result = logging.Formatter(fmt, dfmt)
return result
-
+
def configure_filter(self, config):
"""Configure a filter from a dictionary."""
if '()' in config:
@@ -463,7 +470,8 @@ class DictConfigurator(BaseConfigurator):
filters = config.pop('filters', None)
if '()' in config:
c = config.pop('()')
- if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
+ if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and \
+ type(c) != types.ClassType:
c = self.resolve(c)
factory = c
else:
@@ -472,7 +480,9 @@ class DictConfigurator(BaseConfigurator):
if issubclass(klass, logging.handlers.MemoryHandler) and\
'target' in config:
try:
- config['target'] = self.config['handlers'][config['target']]
+ config['target'] = self.config['handlers'][
+ config['target']
+ ]
except StandardError, e:
raise ValueError('Unable to set target handler '
'%r: %s' % (config['target'], e))
@@ -528,7 +538,7 @@ class DictConfigurator(BaseConfigurator):
filters = config.get('filters', None)
if filters:
self.add_filters(logger, filters)
-
+
def configure_logger(self, name, config, incremental=False):
"""Configure a non-root logger from a dictionary."""
logger = logging.getLogger(name)
@@ -536,7 +546,7 @@ class DictConfigurator(BaseConfigurator):
propagate = config.get('propagate', None)
if propagate is not None:
logger.propagate = propagate
-
+
def configure_root(self, config, incremental=False):
"""Configure a root logger from a dictionary."""
root = logging.getLogger()
@@ -544,6 +554,7 @@ class DictConfigurator(BaseConfigurator):
dictConfigClass = DictConfigurator
+
def dictConfig(config):
"""Configure logging using a dictionary."""
dictConfigClass(config).configure()