Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable more rules for ruff #562

Merged
merged 26 commits into from
Jul 5, 2024
36 changes: 14 additions & 22 deletions constance/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ def __init__(self, model, admin_site):
super().__init__(model, admin_site)

def get_urls(self):
info = self.model._meta.app_label, self.model._meta.module_name
info = f'{self.model._meta.app_label}_{self.model._meta.module_name}'
return [
path('', self.admin_site.admin_view(self.changelist_view), name='%s_%s_changelist' % info),
path('', self.admin_site.admin_view(self.changelist_view), name='%s_%s_add' % info),
path('', self.admin_site.admin_view(self.changelist_view), name=f'{info}_changelist'),
path('', self.admin_site.admin_view(self.changelist_view), name=f'{info}_add'),
]

def get_config_value(self, name, options, form, initial):
Expand Down Expand Up @@ -73,9 +73,7 @@ def get_config_value(self, name, options, form, initial):
return config_value

def get_changelist_form(self, request):
"""
Returns a Form class for use in the changelist_view.
"""
"""Returns a Form class for use in the changelist_view."""
# Defaults to self.change_list_form in order to preserve backward
# compatibility
return self.change_list_form
Expand All @@ -91,18 +89,9 @@ def changelist_view(self, request, extra_context=None):
form = form_cls(data=request.POST, files=request.FILES, initial=initial, request=request)
if form.is_valid():
form.save()
messages.add_message(
request,
messages.SUCCESS,
_('Live settings updated successfully.'),
)
messages.add_message(request, messages.SUCCESS, _('Live settings updated successfully.'))
return HttpResponseRedirect('.')
else:
messages.add_message(
request,
messages.ERROR,
_('Failed to update live settings.'),
)
messages.add_message(request, messages.ERROR, _('Failed to update live settings.'))
context = dict(
self.admin_site.each_context(request),
config_values=[],
Expand All @@ -125,17 +114,20 @@ def changelist_view(self, request, extra_context=None):

context['fieldsets'] = []
for fieldset_title, fieldset_data in fieldset_items:
if type(fieldset_data) == dict:
if isinstance(fieldset_data, dict):
fields_list = fieldset_data['fields']
collapse = fieldset_data.get('collapse', False)
else:
fields_list = fieldset_data
collapse = False

absent_fields = [field for field in fields_list if field not in settings.CONFIG]
assert not any(absent_fields), (
'CONSTANCE_CONFIG_FIELDSETS contains field(s) that does ' 'not exist: %s' % ', '.join(absent_fields)
)
if any(absent_fields):
raise ValueError(
'CONSTANCE_CONFIG_FIELDSETS contains field(s) that does not exist(s): {}'.format(
Mogost marked this conversation as resolved.
Show resolved Hide resolved
', '.join(absent_fields)
)
)

config_values = []

Expand Down Expand Up @@ -182,7 +174,7 @@ def get_ordered_objects(self):
return False

def get_change_permission(self):
return 'change_%s' % self.model_name
return f'change_{self.model_name}'

@property
def app_config(self):
Expand Down
3 changes: 0 additions & 3 deletions constance/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,3 @@ class ConstanceConfig(AppConfig):
name = 'constance'
verbose_name = _('Constance')
default_auto_field = 'django.db.models.AutoField'

def ready(self):
from . import checks
sergei-iurchenko marked this conversation as resolved.
Show resolved Hide resolved
8 changes: 2 additions & 6 deletions constance/backends/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Defines the base constance backend
"""
"""Defines the base constance backend."""


class Backend:
Expand All @@ -19,7 +17,5 @@ def mget(self, keys):
raise NotImplementedError

def set(self, key, value):
"""
Add the value to the backend store given the key.
"""
"""Add the value to the backend store given the key."""
raise NotImplementedError
6 changes: 3 additions & 3 deletions constance/backends/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ def __init__(self):
if isinstance(self._cache, LocMemCache):
raise ImproperlyConfigured(
'The CONSTANCE_DATABASE_CACHE_BACKEND setting refers to a '
"subclass of Django's local-memory backend (%r). Please "
'set it to a backend that supports cross-process caching.' % settings.DATABASE_CACHE_BACKEND
f"subclass of Django's local-memory backend ({settings.DATABASE_CACHE_BACKEND!r}). Please "
'set it to a backend that supports cross-process caching.'
)
else:
self._cache = None
Expand Down Expand Up @@ -102,7 +102,7 @@ def set(self, key, value):
with transaction.atomic(using=queryset.db):
queryset.create(key=key, value=value)
created = True
except IntegrityError as error:
except IntegrityError:
# Allow concurrent writes
constance = queryset.get(key=key)

Expand Down
11 changes: 5 additions & 6 deletions constance/backends/memory.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from threading import Lock

from .. import config
from .. import signals
from constance import config
from constance import signals

from . import Backend


class MemoryBackend(Backend):
"""
Simple in-memory backend that should be mostly used for testing purposes
"""
"""Simple in-memory backend that should be mostly used for testing purposes."""

_storage = {}
_lock = Lock()
Expand All @@ -22,7 +21,7 @@ def get(self, key):

def mget(self, keys):
if not keys:
return
return None
result = []
with self._lock:
for key in keys:
Expand Down
15 changes: 8 additions & 7 deletions constance/backends/redisd.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@

from django.core.exceptions import ImproperlyConfigured

from .. import config
from .. import settings
from .. import signals
from .. import utils
from constance import config
from constance import settings
from constance import signals
from constance import utils

from . import Backend


Expand All @@ -23,7 +24,7 @@ def __init__(self):
try:
import redis
except ImportError:
raise ImproperlyConfigured('The Redis backend requires redis-py to be installed.')
raise ImproperlyConfigured('The Redis backend requires redis-py to be installed.') from None
sergei-iurchenko marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(settings.REDIS_CONNECTION, str):
self._rd = redis.from_url(settings.REDIS_CONNECTION)
else:
Expand All @@ -35,7 +36,7 @@ def add_prefix(self, key):
def get(self, key):
value = self._rd.get(self.add_prefix(key))
if value:
return loads(value)
return loads(value) # noqa: S301
sergei-iurchenko marked this conversation as resolved.
Show resolved Hide resolved
return None

def mget(self, keys):
Expand All @@ -44,7 +45,7 @@ def mget(self, keys):
prefixed_keys = [self.add_prefix(key) for key in keys]
for key, value in zip(keys, self._rd.mget(prefixed_keys)):
if value:
yield key, loads(value)
yield key, loads(value) # noqa: S301

def set(self, key, value):
old_value = self.get(key)
Expand Down
10 changes: 4 additions & 6 deletions constance/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,18 @@


class Config:
"""
The global config wrapper that handles the backend.
"""
"""The global config wrapper that handles the backend."""

def __init__(self):
super().__setattr__('_backend', utils.import_module_attr(settings.BACKEND)())

def __getattr__(self, key):
try:
if not len(settings.CONFIG[key]) in (2, 3):
if len(settings.CONFIG[key]) not in (2, 3):
raise AttributeError(key)
default = settings.CONFIG[key][0]
except KeyError:
raise AttributeError(key)
except KeyError as e:
raise AttributeError(key) from e
result = self._backend.get(key)
if result is None:
result = default
Expand Down
14 changes: 6 additions & 8 deletions constance/checks.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
from typing import List
from typing import Set
from typing import Tuple
from __future__ import annotations

from django.core import checks
from django.core.checks import CheckMessage
from django.utils.translation import gettext_lazy as _


@checks.register('constance')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🙏

def check_fieldsets(*args, **kwargs) -> List[CheckMessage]:
def check_fieldsets(*args, **kwargs) -> list[CheckMessage]:
"""
A Django system check to make sure that, if defined,
CONFIG_FIELDSETS is consistent with settings.CONFIG.
Expand All @@ -21,15 +19,15 @@ def check_fieldsets(*args, **kwargs) -> List[CheckMessage]:
missing_keys, extra_keys = get_inconsistent_fieldnames()
if missing_keys:
check = checks.Warning(
_('CONSTANCE_CONFIG_FIELDSETS is missing ' 'field(s) that exists in CONSTANCE_CONFIG.'),
_('CONSTANCE_CONFIG_FIELDSETS is missing field(s) that exists in CONSTANCE_CONFIG.'),
hint=', '.join(sorted(missing_keys)),
obj='settings.CONSTANCE_CONFIG',
id='constance.E001',
)
errors.append(check)
if extra_keys:
check = checks.Warning(
_('CONSTANCE_CONFIG_FIELDSETS contains extra ' 'field(s) that does not exist in CONFIG.'),
_('CONSTANCE_CONFIG_FIELDSETS contains extra field(s) that does not exist in CONFIG.'),
hint=', '.join(sorted(extra_keys)),
obj='settings.CONSTANCE_CONFIG',
id='constance.E002',
Expand All @@ -38,7 +36,7 @@ def check_fieldsets(*args, **kwargs) -> List[CheckMessage]:
return errors


def get_inconsistent_fieldnames() -> Tuple[Set, Set]:
def get_inconsistent_fieldnames() -> tuple[set, set]:
"""
Returns a pair of values:
1) set of keys from settings.CONFIG that are not accounted for in settings.CONFIG_FIELDSETS
Expand All @@ -53,7 +51,7 @@ def get_inconsistent_fieldnames() -> Tuple[Set, Set]:
fieldset_items = settings.CONFIG_FIELDSETS

unique_field_names = set()
for fieldset_title, fields_list in fieldset_items:
for _fieldset_title, fields_list in fieldset_items:
# fields_list can be a dictionary, when a fieldset is defined as collapsible
# https://django-constance.readthedocs.io/en/latest/#fieldsets-collapsing
if isinstance(fields_list, dict) and 'fields' in fields_list:
Expand Down
2 changes: 1 addition & 1 deletion constance/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def clean(self):
missing_keys, extra_keys = get_inconsistent_fieldnames()
if missing_keys or extra_keys:
raise forms.ValidationError(
_('CONSTANCE_CONFIG_FIELDSETS is missing ' 'field(s) that exists in CONSTANCE_CONFIG.')
_('CONSTANCE_CONFIG_FIELDSETS is missing field(s) that exists in CONSTANCE_CONFIG.')
)

return cleaned_data
19 changes: 9 additions & 10 deletions constance/management/commands/constance.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
from django.core.management import CommandError
from django.utils.translation import gettext as _

from ... import config
from ...forms import ConstanceForm
from ...models import Constance
from ...utils import get_values
from constance import config
from constance.forms import ConstanceForm
from constance.models import Constance
from constance.utils import get_values


def _set_constance_value(key, value):
Expand All @@ -17,7 +17,6 @@ def _set_constance_value(key, value):
:param value:
:return:
"""

form = ConstanceForm(initial=get_values())

field = form.fields[key]
Expand Down Expand Up @@ -55,18 +54,18 @@ def handle(self, command, key=None, value=None, *args, **options):
if command == self.GET:
try:
self.stdout.write(str(getattr(config, key)), ending='\n')
except AttributeError:
raise CommandError(f'{key} is not defined in settings.CONSTANCE_CONFIG')
except AttributeError as e:
raise CommandError(f'{key} is not defined in settings.CONSTANCE_CONFIG') from e
elif command == self.SET:
try:
if len(value) == 1:
# assume that if a single argument was passed, the field doesn't expect a list
value = value[0]
_set_constance_value(key, value)
except KeyError:
raise CommandError(f'{key} is not defined in settings.CONSTANCE_CONFIG')
except KeyError as e:
raise CommandError(f'{key} is not defined in settings.CONSTANCE_CONFIG') from e
except ValidationError as e:
raise CommandError(', '.join(e))
raise CommandError(', '.join(e)) from e
elif command == self.LIST:
for k, v in get_values().items():
self.stdout.write(f'{k}\t{v}', ending='\n')
Expand Down
5 changes: 3 additions & 2 deletions constance/migrations/0002_migrate_from_old_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ def _migrate_from_old_table(apps, schema_editor) -> None:
try:
with connection.cursor() as cursor:
cursor.execute(
f'INSERT INTO constance_constance ( {quoted_string} ) SELECT {quoted_string} FROM constance_config', []
f'INSERT INTO constance_constance ( {quoted_string} ) SELECT {quoted_string} FROM constance_config', # noqa: S608
[],
)
cursor.execute('DROP TABLE constance_config', [])
except DatabaseError as exc:
except DatabaseError:
logger.exception('copy data from old constance table to a new one')

Constance = apps.get_model('constance', 'Constance')
Expand Down
2 changes: 1 addition & 1 deletion constance/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"Couldn't find the the 3rd party app "
'django-picklefield which is required for '
'the constance database backend.'
)
) from None
sergei-iurchenko marked this conversation as resolved.
Show resolved Hide resolved


class Constance(models.Model):
Expand Down
2 changes: 2 additions & 0 deletions constance/test/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from .unittest import override_config # pragma: no cover

__all__ = ['override_config']
Mogost marked this conversation as resolved.
Show resolved Hide resolved
Loading