Skip to content

Commit

Permalink
Switch to f-strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
idlesign committed May 1, 2020
1 parent c9b26e6 commit 88f0abf
Show file tree
Hide file tree
Showing 39 changed files with 135 additions and 178 deletions.
10 changes: 0 additions & 10 deletions tests/contrib/test_django.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

import pytest

PY2 = (version_info[0] == 2)


@pytest.fixture
def patch_project_dir(monkeypatch):
Expand Down Expand Up @@ -40,15 +38,13 @@ class Error(Exception):
lambda project_name: '%s' % fifofile)


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_mutate_existing_section(patch_base_command):
from uwsgiconf.contrib.django.uwsgify.toolbox import SectionMutator

mutator = SectionMutator.spawn(dir_base=os.path.dirname(__file__))
assert mutator.section.name == 'testdummy'


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_uwsgi_run(monkeypatch, patch_project_dir, stub):

class Settings(object):
Expand Down Expand Up @@ -82,35 +78,30 @@ class Settings(object):
Command().handle(compile=False, contribute_static=True, embedded=True)


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_uwsgi_log(patch_base_command):
from uwsgiconf.contrib.django.uwsgify.management.commands.uwsgi_log import Command

Command().handle(reopen=True, rotate=False)


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_uwsgi_reload(patch_base_command):
from uwsgiconf.contrib.django.uwsgify.management.commands.uwsgi_reload import Command

Command().handle(force=False, workers=False, chain=False)


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_uwsgi_stats(patch_base_command):
from uwsgiconf.contrib.django.uwsgify.management.commands.uwsgi_stats import Command

Command().handle()


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_uwsgi_stop(patch_base_command):
from uwsgiconf.contrib.django.uwsgify.management.commands.uwsgi_stop import Command

Command().handle(force=False)


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_uwsgi_sysinit_systemd(patch_base_command, capsys):
from uwsgiconf.contrib.django.uwsgify.management.commands.uwsgi_sysinit import Command

Expand All @@ -129,7 +120,6 @@ def test_uwsgi_sysinit_systemd(patch_base_command, capsys):
assert 'dummy/manage.py uwsgi_run --nostatic --noruntimes\n' in out


@pytest.mark.skipif(PY2, reason='Not tested on PY2')
def test_uwsgi_sysinit_upstart(patch_base_command, capsys):
from uwsgiconf.contrib.django.uwsgify.management.commands.uwsgi_sysinit import Command

Expand Down
8 changes: 4 additions & 4 deletions uwsgiconf/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, key):
def swap(self, new_key):

if new_key:
self.key = '%s' % new_key
self.key = f'{new_key}'

def __str__(self):
return self.key
Expand Down Expand Up @@ -110,10 +110,10 @@ def __call__(self, *args, **kwargs):
return self.set_basic_params(*args, **kwargs)

def __eq__(self, obj):
return '%s' % self == obj
return f'{self}' == obj

def __hash__(self):
return hash('%s' % self)
return hash(f'{self}')

def set_basic_params(self, *args, **kwargs):
"""
Expand Down Expand Up @@ -270,7 +270,7 @@ def __str__(self):
result += self.args_joiner.join(args)

if self.alias:
result = '%s %s' % (self.alias, result)
result = f'{self.alias} {result}'

result = result.strip()

Expand Down
4 changes: 2 additions & 2 deletions uwsgiconf/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def errorprint():
yield

except ConfigurationError as e:
click.secho('%s' % e, err=True, fg='red')
click.secho(f'{e}', err=True, fg='red')
sys.exit(1)


Expand Down Expand Up @@ -45,7 +45,7 @@ def run(conf, only):
spawned = config.spawn_uwsgi(only)

for alias, pid in spawned:
click.secho("Spawned uWSGI for configuration aliased '%s'. PID %s" % (alias, pid), fg='green')
click.secho(f"Spawned uWSGI for configuration aliased '{alias}'. PID {pid}", fg='green')


@base.command()
Expand Down
28 changes: 18 additions & 10 deletions uwsgiconf/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def get_runtime_dir(self, default=True):

if not dir_ and default:
uid = self.main_process.get_owner()[0]
dir_ = '/run/user/%s/' % uid if uid else '/run/'
dir_ = f'/run/user/{uid}/' if uid else '/run/'

return dir_

Expand Down Expand Up @@ -279,7 +279,11 @@ def print_stamp(self):

print_out = partial(self.print_out, format_options='red')
print_out('This configuration was automatically generated using')
print_out('uwsgiconf v%s on %s' % ('.'.join(map(str, VERSION)), datetime.now().isoformat(' ')))
print_out(
'uwsgiconf v%s on %s' % (
'.'.join(map(str, VERSION)),
datetime.now().isoformat(' ')
))

return self

Expand Down Expand Up @@ -387,7 +391,7 @@ def set_placeholder(self, key, value):
:param str|unicode value:
"""
self._set('set-placeholder', '%s=%s' % (key, value), multi=True)
self._set('set-placeholder', f'{key}={value}', multi=True)

return self

Expand All @@ -411,7 +415,11 @@ def env(self, key, value=None, unset=False, asap=False):
if value is None:
value = os.environ.get(key)

self._set('%senv' % ('i' if asap else ''), '%s=%s' % (key, value), multi=True)
self._set(
f"{'i' if asap else ''}env",
f'{key}={value}',
multi=True
)

return self

Expand Down Expand Up @@ -480,7 +488,7 @@ class vars(object):
FORMAT_ESCAPE = '%['
"""ANSI escape \\033. useful for printing colors"""

FORMAT_END = '%s[0m' % FORMAT_ESCAPE
FORMAT_END = f'{FORMAT_ESCAPE}[0m'

CONF_CURRENT_SECTION = '%x'
"""The current section identifier, eg. conf.ini:section."""
Expand Down Expand Up @@ -632,7 +640,7 @@ def _validate_sections(cls, sections):

name = section.name
if name in names:
raise ConfigurationError('`%s` section name must be unique' % name)
raise ConfigurationError(f'`{name}` section name must be unique')

names.append(name)

Expand Down Expand Up @@ -674,14 +682,14 @@ def tofile(self, filepath=None):
"""
if filepath is None:
with NamedTemporaryFile(prefix='%s_' % self.alias, suffix='.ini', delete=False) as f:
with NamedTemporaryFile(prefix=f'{self.alias}_', suffix='.ini', delete=False) as f:
filepath = f.name

else:
filepath = os.path.abspath(filepath)

if os.path.isdir(filepath):
filepath = os.path.join(filepath, '%s.ini' % self.alias)
filepath = os.path.join(filepath, f'{self.alias}.ini')

with open(filepath, 'w') as target_file:
target_file.write(self.format())
Expand Down Expand Up @@ -743,8 +751,8 @@ def configure_uwsgi(configurator_func):

if alias in registry:
raise ConfigurationError(
"Configuration alias '%s' clashes with another configuration. "
"Please change the alias." % alias)
f"Configuration alias '{alias}' clashes with another configuration. "
"Please change the alias.")

registry[alias] = conf_candidate

Expand Down
10 changes: 7 additions & 3 deletions uwsgiconf/contrib/django/uwsgify/admin/realms.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@ def get_func_name(func):
:rtype: str
"""
module_path = func.__module__

if module_path.startswith('uwsgi_file'):
module_path = module_path.replace('uwsgi_file__', 'uwsgi://', 1).replace('_', '/')
return '%s.%s' % (module_path, func.__name__)

return f'{module_path}.{func.__name__}'

def get_signals_info(signals):
info = []

for signal in signals:
info.append('%s - %s: %s' % (signal.num, signal.target, get_func_name(signal.func)))
info.append(f'{signal.num} - {signal.target}: {get_func_name(signal.func)}')

return info

time_started = datetime.fromtimestamp(uwsgi.started_on)
Expand Down Expand Up @@ -152,7 +156,7 @@ def iter_items(info, mapping):
if keyname_worker == 'apps':
# Get info about applications served by worker,
for idx_app, keyname_app, name_app, value_app in value_worker:
app_key = '%s %s. %s %s' % (_('Worker'), idx_worker + 1, _('Application'), idx_app)
app_key = f'%s {idx_worker + 1}. %s {idx_app}' % (_('Worker'), _('Application'))
info_apps.setdefault(app_key, OrderedDict())[name_app] = [value_app]

else:
Expand Down
5 changes: 3 additions & 2 deletions uwsgiconf/contrib/django/uwsgify/management/commands/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,6 @@ def handle(self, *args, **options):

else:
raise CommandError(
'Unable to find uWSGI FIFO file for "%s" project in %s' %
(mutator.section.project_name, filepath))
'Unable to find uWSGI FIFO file '
f'for "{mutator.section.project_name}" project in {filepath}'
)
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def handle(self, *args, **options):

for opt in ('nostatic', 'noruntimes', 'noerrpages'):
if options.get(opt, False):
command = command + ' --%s' % opt
command = command + f' --{opt}'

config = get_config(
systype,
Expand Down
30 changes: 9 additions & 21 deletions uwsgiconf/contrib/django/uwsgify/toolbox.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import importlib.util
import inspect
import os
from importlib import import_module

from uwsgiconf.presets.nice import PythonSection
from uwsgiconf.settings import CONFIGS_MODULE_ATTR
from uwsgiconf.utils import ConfModule, UwsgiRunner, PY3
from uwsgiconf.utils import ConfModule, UwsgiRunner

if False: # pragma: nocover
from uwsgiconf.base import Section
Expand Down Expand Up @@ -136,13 +137,7 @@ def _get_section_existing(self, path_conf, name_module, name_project, embedded=F
"""
def load():
module_fake_name = '%s.%s' % (name_project, os.path.splitext(name_module)[0])

if not PY3: # pragma: nocover
import imp
return imp.load_source(module_fake_name, path_conf)

import importlib.util
module_fake_name = f'{name_project}.{os.path.splitext(name_module)[0]}'

spec = importlib.util.spec_from_file_location(module_fake_name, path_conf)
module = importlib.util.module_from_spec(spec)
Expand All @@ -152,9 +147,9 @@ def load():

if embedded:
try:
module = import_module('%s.%s' % (name_project, name_module.rstrip('.py')))
module = import_module(f"{name_project}.{name_module.rstrip('.py')}")

except ImportError: # py3 - ModuleNotFoundError
except ModuleNotFoundError:
return None

else:
Expand Down Expand Up @@ -183,7 +178,7 @@ def _get_section_new(cls, dir_base):

section = PythonSection.bootstrap(
'http://127.0.0.1:8000',
wsgi_module='%s.%s' % (name_package, name_module),
wsgi_module=f'{name_package}.{name_module}',
)

if os.path.exists(dir_base):
Expand Down Expand Up @@ -231,14 +226,7 @@ def contribute_runtime_dir(self):
section.set_runtime_dir(section.get_runtime_dir())

if not self.options['compile']:
if PY3:
os.makedirs(self.runtime_dir, 0o755, True)
else:
try:
os.makedirs(self.runtime_dir, 0o755)

except OSError: # simulate exist_ok
pass
os.makedirs(self.runtime_dir, 0o755, True)

def mutate(self, embedded=False):
"""Mutates current section."""
Expand All @@ -263,10 +251,10 @@ def mutate(self, embedded=False):
)

else:
main.set_naming_params(prefix='[%s] ' % project_name)
main.set_naming_params(prefix=f'[{project_name}] ')

section.print_out(
'Embedded mode: %s' % ('yes' if embedded else 'no'),
f"Embedded mode: {'yes' if embedded else 'no'}",
format_options='blue')

# todo maybe autoreload in debug
Expand Down
6 changes: 2 additions & 4 deletions uwsgiconf/contrib/django/uwsgify/uwsgiinit.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals

from django import db
from django.apps import apps
from django.utils.module_loading import autodiscover_modules
Expand All @@ -26,7 +23,8 @@ def check_for_stub():
msg = (
'Something from uwsgiconf.uwsgi has been imported before uWSGI start. '
'Please move uWSGI related stuff including such imports '
'into %s.py modules of your apps.' % MODULE_INIT)
f'into {MODULE_INIT}.py modules of your apps.'
)

raise RuntimeConfigurationError(msg)

Expand Down
8 changes: 4 additions & 4 deletions uwsgiconf/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,10 @@ def format(self):
for section_name, key, value in self.iter_options():

if section_name != last_section:
lines.append('\n[%s]' % section_name)
lines.append(f'\n[{section_name}]')
last_section = section_name

lines.append('%s = %s' % (key, str(value).strip()))
lines.append(f'{key} = {str(value).strip()}')

lines = '\n'.join(lines)
return lines
Expand All @@ -120,14 +120,14 @@ def format(self):
value = str(value).strip()

if value == 'true':
lines.append('--%s' % key)
lines.append(f'--{key}')

elif value.startswith('%') and len(value) == 2:
# No config var support is available in command line.
continue

else:
lines.extend(['--%s' % key, '%s' % value])
lines.extend([f'--{key}', f'{value}'])

return lines

Expand Down
Loading

0 comments on commit 88f0abf

Please sign in to comment.