Skip to content

Commit

Permalink
Use more str.format
Browse files Browse the repository at this point in the history
  • Loading branch information
ask committed Jul 22, 2012
1 parent b194fc3 commit b23fd8c
Show file tree
Hide file tree
Showing 61 changed files with 358 additions and 324 deletions.
2 changes: 1 addition & 1 deletion celery/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
__contact__ = '[email protected]'
__homepage__ = 'http://celeryproject.org'
__docformat__ = 'restructuredtext'
VERSION_BANNER = '%s (%s)' % (__version__, SERIES)
VERSION_BANNER = '{0} ({1})'.format(__version__, SERIES)

# -eof meta-

Expand Down
11 changes: 4 additions & 7 deletions celery/app/amqp.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@

#: Human readable queue declaration.
QUEUE_FORMAT = """
. %(name)s exchange:%(exchange)s(%(exchange_type)s) binding:%(routing_key)s
. {0.name:<16} exchange={0.exchange.name}({0.exchange.type}) \
key={0.routing_key}
"""


Expand Down Expand Up @@ -102,12 +103,8 @@ def format(self, indent=0, indent_first=True):
active = self.consume_from
if not active:
return ''
info = [QUEUE_FORMAT.strip() % {
'name': (name + ':').ljust(12),
'exchange': q.exchange.name,
'exchange_type': q.exchange.type,
'routing_key': q.routing_key}
for name, q in sorted(active.iteritems())]
info = [QUEUE_FORMAT.strip().format(q)
for _, q in sorted(active.iteritems())]
if indent_first:
return textindent('\n'.join(info), indent)
return info[0] + '\n' + textindent('\n'.join(info[1:]), indent)
Expand Down
2 changes: 1 addition & 1 deletion celery/app/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def expand_destination(self, route):
except KeyError:
if not self.create_missing:
raise QueueNotFound(
'Queue %r is not defined in CELERY_QUEUES' % queue)
'Queue {0!r} missing from CELERY_QUEUES'.format(queue))
for key in 'exchange', 'routing_key':
if route.get(key) is None:
route[key] = queue
Expand Down
44 changes: 22 additions & 22 deletions celery/app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@

#: Format used to generate bugreport information.
BUGREPORT_INFO = """
software -> celery:%(celery_v)s kombu:%(kombu_v)s py:%(py_v)s
billiard:%(billiard_v)s %(driver_v)s
platform -> system:%(system)s arch:%(arch)s imp:%(py_i)s
loader -> %(loader)s
settings -> transport:%(transport)s results:%(results)s
software -> celery:{celery_v} kombu:{kombu_v} py:{py_v}
billiard:{billiard_v} {driver_v}
platform -> system:{system} arch:{arch} imp:{py_i}
loader -> {loader}
settings -> transport:{transport} results:{results}
%(human_settings)s
{human_settings}
"""


Expand Down Expand Up @@ -90,7 +90,7 @@ def get_by_parts(self, *parts):
def humanize(self):
"""Returns a human readable string showing changes to the
configuration."""
return '\n'.join('%s %s' % (key + ':', pretty(value, width=50))
return '\n'.join('{0}: {1}'.format(key, pretty(value, width=50))
for key, value in self.without_defaults().iteritems())


Expand Down Expand Up @@ -132,21 +132,21 @@ def bugreport(app):

try:
trans = app.connection().transport
driver_v = '%s:%s' % (trans.driver_name, trans.driver_version())
driver_v = '{0}:{1}'.format(trans.driver_name, trans.driver_version())
except Exception:
driver_v = ''

return BUGREPORT_INFO % {
'system': _platform.system(),
'arch': ', '.join(filter(None, _platform.architecture())),
'py_i': platforms.pyimplementation(),
'celery_v': celery.VERSION_BANNER,
'kombu_v': kombu.__version__,
'billiard_v': billiard.__version__,
'py_v': _platform.python_version(),
'driver_v': driver_v,
'transport': app.conf.BROKER_TRANSPORT or 'amqp',
'results': app.conf.CELERY_RESULT_BACKEND or 'disabled',
'human_settings': app.conf.humanize(),
'loader': qualname(app.loader.__class__),
}
return BUGREPORT_INFO.format(
system=_platform.system(),
arch=', '.join(filter(None, _platform.architecture())),
py_i=platforms.pyimplementation(),
celery_v=celery.VERSION_BANNER,
kombu_v=kombu.__version__,
billiard_v=billiard.__version__,
py_v=_platform.python_version(),
driver_v=driver_v,
transport= app.conf.BROKER_TRANSPORT or 'amqp',
results=app.conf.CELERY_RESULT_BACKEND or 'disabled',
human_settings=app.conf.humanize(),
loader=qualname(app.loader.__class__),
)
34 changes: 17 additions & 17 deletions celery/apps/beat.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@

STARTUP_INFO_FMT = """
Configuration ->
. broker -> %(conninfo)s
. loader -> %(loader)s
. scheduler -> %(scheduler)s
%(scheduler_info)s
. logfile -> %(logfile)s@%(loglevel)s
. maxinterval -> %(hmax_interval)s (%(max_interval)ss)
. broker -> {conninfo}
. loader -> {loader}
. scheduler -> {scheduler}
{scheduler_info}
. logfile -> {logfile}@%{loglevel}
. maxinterval -> {hmax_interval} ({max_interval}s)
""".strip()

logger = get_logger('celery.beat')
Expand Down Expand Up @@ -62,7 +62,7 @@ def __init__(self, max_interval=None, app=None,

def run(self):
print(str(self.colored.cyan(
'celerybeat v%s is starting.' % VERSION_BANNER)))
'celerybeat v{0} is starting.'.format(VERSION_BANNER))))
self.init_loader()
self.set_process_title()
self.start_scheduler()
Expand Down Expand Up @@ -108,16 +108,16 @@ def init_loader(self):

def startup_info(self, beat):
scheduler = beat.get_scheduler(lazy=True)
return STARTUP_INFO_FMT % {
'conninfo': self.app.connection().as_uri(),
'logfile': self.logfile or '[stderr]',
'loglevel': LOG_LEVELS[self.loglevel],
'loader': qualname(self.app.loader),
'scheduler': qualname(scheduler),
'scheduler_info': scheduler.info,
'hmax_interval': humanize_seconds(beat.max_interval),
'max_interval': beat.max_interval,
}
return STARTUP_INFO_FMT.format(
conninfo=self.app.connection().as_uri(),
logfile=self.logfile or '[stderr]',
loglevel=LOG_LEVELS[self.loglevel],
loader=qualname(self.app.loader),
scheduler=qualname(scheduler),
scheduler_info=scheduler.info,
hmax_interval=humanize_seconds(beat.max_interval),
max_interval=beat.max_interval,
)

def set_process_title(self):
arg_start = 'manage' in sys.argv[0] and 2 or 1
Expand Down
8 changes: 3 additions & 5 deletions celery/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,7 @@ def prepare_value(self, result):
return result

def forget(self, task_id):
raise NotImplementedError('%s does not implement forget.' % (
self.__class__))
raise NotImplementedError('backend does not implement forget.')

def wait_for(self, task_id, timeout=None, propagate=True, interval=0.5):
"""Wait for task and return its result.
Expand Down Expand Up @@ -259,8 +258,7 @@ def forget(self, task_id):
self._forget(task_id)

def _forget(self, task_id):
raise NotImplementedError('%s does not implement forget.' % (
self.__class__))
raise NotImplementedError('backend does not implement forget.')

def get_status(self, task_id):
"""Get the status of a task."""
Expand Down Expand Up @@ -411,7 +409,7 @@ def get_many(self, task_ids, timeout=None, interval=0.5):
for key, value in r.iteritems():
yield bytes_to_str(key), value
if timeout and iterations * interval >= timeout:
raise TimeoutError('Operation timed out (%s)' % (timeout, ))
raise TimeoutError('Operation timed out ({0})'.format(timeout))
time.sleep(interval) # don't busy loop.
iterations += 0

Expand Down
8 changes: 4 additions & 4 deletions celery/backends/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ def __init__(self, expires=None, backend=None, options={}, **kwargs):
self.Client = backends[self.backend]()
except KeyError:
raise ImproperlyConfigured(
'Unknown cache backend: %s. Please use one of the '
'following backends: %s' % (self.backend,
', '.join(backends.keys())))
'Unknown cache backend: {0}. Please use one of the '
'following backends: {1}'.format(self.backend,
', '.join(backends.keys())))

def get(self, key):
return self.client.get(key)
Expand All @@ -119,7 +119,7 @@ def client(self):

def __reduce__(self, args=(), kwargs={}):
servers = ';'.join(self.servers)
backend = '%s://%s/' % (self.backend, servers)
backend = '{0}://{1}/'.format(self.backend, servers)
kwargs.update(
dict(backend=backend,
expires=self.expires,
Expand Down
4 changes: 2 additions & 2 deletions celery/backends/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def to_dict(self):
'date_done': self.date_done}

def __repr__(self):
return '<Task %s state: %s>' % (self.task_id, self.status)
return '<Task {0.task_id} state: {0.status}>'.format(self)


class TaskSet(ResultModelBase):
Expand All @@ -69,4 +69,4 @@ def to_dict(self):
'date_done': self.date_done}

def __repr__(self):
return '<TaskSet: %s>' % (self.taskset_id, )
return '<TaskSet: {0.taskset_id}>'.format(self)
4 changes: 2 additions & 2 deletions celery/backends/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ def __init__(self, host=None, port=None, db=None, password=None,

# For compatibility with the old REDIS_* configuration keys.
def _get(key):
for prefix in 'CELERY_REDIS_%s', 'REDIS_%s':
for prefix in 'CELERY_REDIS_{0}', 'REDIS_{0}':
try:
return conf[prefix % key]
return conf[prefix.format(key)]
except KeyError:
pass
if host and '://' in host:
Expand Down
13 changes: 6 additions & 7 deletions celery/beat.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,8 @@ def __iter__(self):
return vars(self).iteritems()

def __repr__(self):
return ('<Entry: %s %s {%s}' % (self.name,
reprcall(self.task, self.args or (), self.kwargs or {}),
self.schedule))
return '<Entry: {0.name} {call} {0.schedule}'.format(self,
call=reprcall(self.task, self.args or (), self.kwargs or {}))


class Scheduler(object):
Expand Down Expand Up @@ -225,8 +224,8 @@ def apply_async(self, entry, publisher=None, **kwargs):
**entry.options)
except Exception as exc:
raise SchedulingError, SchedulingError(
"Couldn't apply scheduled task %s: %s" % (
entry.name, exc)), sys.exc_info()[2]
"Couldn't apply scheduled task {0.name}: {exc}".format(
entry, exc)), sys.exc_info()[2]
finally:
if self.should_sync():
self._do_sync()
Expand Down Expand Up @@ -370,7 +369,7 @@ def close(self):

@property
def info(self):
return ' . db -> %s' % (self.schedule_filename, )
return ' . db -> {self.schedule_filename}'.format(self=self)


class Service(object):
Expand Down Expand Up @@ -473,7 +472,7 @@ def EmbeddedService(*args, **kwargs):
"""Return embedded clock service.
:keyword thread: Run threaded instead of as a separate process.
Default is :const:`False`.
Uses :mod:`multiprocessing` by default, if available.
"""
if kwargs.pop('thread', False) or _Process is None:
Expand Down
20 changes: 10 additions & 10 deletions celery/bin/camqadm.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,11 @@ def format_response(self, response):
return response
if callable(self.returns):
return self.returns(response)
return self.returns % (response, )
return self.returns.format(response)

def format_arg(self, name, type, default_value=None):
if default_value is not None:
return '%s:%s' % (name, default_value)
return '{0}:{1}'.format(name, default_value)
return name

def format_signature(self):
Expand All @@ -120,7 +120,7 @@ def dump_message(message):


def format_declare_queue(ret):
return 'ok. queue:%s messages:%s consumers:%s.' % ret
return 'ok. queue:{0} messages:{1} consumers:{2}.'.format(*ret)


class AMQShell(cmd.Cmd):
Expand All @@ -144,7 +144,7 @@ class AMQShell(cmd.Cmd):
"""
conn = None
chan = None
prompt_fmt = '%d> '
prompt_fmt = '{self.counter}> '
identchars = cmd.IDENTCHARS = '.'
needs_reconnect = False
counter = 1
Expand Down Expand Up @@ -175,9 +175,9 @@ class AMQShell(cmd.Cmd):
'queue.delete': Spec(('queue', str),
('if_unused', bool, 'no'),
('if_empty', bool, 'no'),
returns='ok. %d messages deleted.'),
returns='ok. {0} messages deleted.'),
'queue.purge': Spec(('queue', str),
returns='ok. %d messages deleted.'),
returns='ok. {0} messages deleted.'),
'basic.get': Spec(('queue', str),
('no_ack', bool, 'off'),
returns=dump_message),
Expand Down Expand Up @@ -233,7 +233,7 @@ def do_exit(self, *args):

def display_command_help(self, cmd, short=False):
spec = self.amqp[cmd]
self.say('%s %s' % (cmd, spec.format_signature()))
self.say('{0} {1}'.format(cmd, spec.format_signature()))

def do_help(self, *args):
if not args:
Expand All @@ -245,7 +245,7 @@ def do_help(self, *args):
self.display_command_help(args[0])

def default(self, line):
self.say("unknown syntax: '%s'. how about some 'help'?" % line)
self.say("unknown syntax: {0!r}. how about some 'help'?".format(line))

def get_names(self):
return set(self.builtins) | set(self.amqp)
Expand Down Expand Up @@ -325,7 +325,7 @@ def _reconnect(self):

@property
def prompt(self):
return self.prompt_fmt % self.counter
return self.prompt_fmt.format(self=self)


class AMQPAdmin(object):
Expand All @@ -342,7 +342,7 @@ def connect(self, conn=None):
if conn:
conn.close()
conn = self.app.connection()
self.note('-> connecting to %s.' % conn.as_uri())
self.note('-> connecting to {0}.'.format(conn.as_uri()))
conn.connect()
self.note('-> connected.')
return conn
Expand Down
Loading

0 comments on commit b23fd8c

Please sign in to comment.