WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit c6b2c44

Browse files
authored
Merge pull request #641 from jazzband/chore/run-black
2 parents c89ee7c + 6d01cff commit c6b2c44

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+625
-622
lines changed

constance/admin.py

Lines changed: 42 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,18 @@
2525

2626

2727
class ConstanceAdmin(admin.ModelAdmin):
28-
change_list_template = 'admin/constance/change_list.html'
28+
change_list_template = "admin/constance/change_list.html"
2929
change_list_form = ConstanceForm
3030

3131
def __init__(self, model, admin_site):
3232
model._meta.concrete_model = Config
3333
super().__init__(model, admin_site)
3434

3535
def get_urls(self):
36-
info = f'{self.model._meta.app_label}_{self.model._meta.module_name}'
36+
info = f"{self.model._meta.app_label}_{self.model._meta.module_name}"
3737
return [
38-
path('', self.admin_site.admin_view(self.changelist_view), name=f'{info}_changelist'),
39-
path('', self.admin_site.admin_view(self.changelist_view), name=f'{info}_add'),
38+
path("", self.admin_site.admin_view(self.changelist_view), name=f"{info}_changelist"),
39+
path("", self.admin_site.admin_view(self.changelist_view), name=f"{info}_add"),
4040
]
4141

4242
def get_config_value(self, name, options, form, initial):
@@ -52,23 +52,23 @@ def get_config_value(self, name, options, form, initial):
5252

5353
form_field = form[name]
5454
config_value = {
55-
'name': name,
56-
'default': localize(default),
57-
'raw_default': default,
58-
'help_text': _(help_text),
59-
'value': localize(value),
60-
'modified': localize(value) != localize(default),
61-
'form_field': form_field,
62-
'is_date': isinstance(default, date),
63-
'is_datetime': isinstance(default, datetime),
64-
'is_checkbox': isinstance(form_field.field.widget, forms.CheckboxInput),
65-
'is_file': isinstance(form_field.field.widget, forms.FileInput),
55+
"name": name,
56+
"default": localize(default),
57+
"raw_default": default,
58+
"help_text": _(help_text),
59+
"value": localize(value),
60+
"modified": localize(value) != localize(default),
61+
"form_field": form_field,
62+
"is_date": isinstance(default, date),
63+
"is_datetime": isinstance(default, datetime),
64+
"is_checkbox": isinstance(form_field.field.widget, forms.CheckboxInput),
65+
"is_file": isinstance(form_field.field.widget, forms.FileInput),
6666
}
6767
if field_type and field_type in settings.ADDITIONAL_FIELDS:
6868
serialized_default = form[name].field.prepare_value(default)
69-
config_value['default'] = serialized_default
70-
config_value['raw_default'] = serialized_default
71-
config_value['value'] = form[name].field.prepare_value(value)
69+
config_value["default"] = serialized_default
70+
config_value["raw_default"] = serialized_default
71+
config_value["value"] = form[name].field.prepare_value(value)
7272

7373
return config_value
7474

@@ -85,47 +85,47 @@ def changelist_view(self, request, extra_context=None):
8585
initial = get_values()
8686
form_cls = self.get_changelist_form(request)
8787
form = form_cls(initial=initial, request=request)
88-
if request.method == 'POST' and request.user.has_perm('constance.change_config'):
88+
if request.method == "POST" and request.user.has_perm("constance.change_config"):
8989
form = form_cls(data=request.POST, files=request.FILES, initial=initial, request=request)
9090
if form.is_valid():
9191
form.save()
92-
messages.add_message(request, messages.SUCCESS, _('Live settings updated successfully.'))
93-
return HttpResponseRedirect('.')
94-
messages.add_message(request, messages.ERROR, _('Failed to update live settings.'))
92+
messages.add_message(request, messages.SUCCESS, _("Live settings updated successfully."))
93+
return HttpResponseRedirect(".")
94+
messages.add_message(request, messages.ERROR, _("Failed to update live settings."))
9595
context = dict(
9696
self.admin_site.each_context(request),
9797
config_values=[],
9898
title=self.model._meta.app_config.verbose_name,
99-
app_label='constance',
99+
app_label="constance",
100100
opts=self.model._meta,
101101
form=form,
102102
media=self.media + form.media,
103-
icon_type='svg',
103+
icon_type="svg",
104104
django_version=get_version(),
105105
)
106106
for name, options in settings.CONFIG.items():
107-
context['config_values'].append(self.get_config_value(name, options, form, initial))
107+
context["config_values"].append(self.get_config_value(name, options, form, initial))
108108

109109
if settings.CONFIG_FIELDSETS:
110110
if isinstance(settings.CONFIG_FIELDSETS, dict):
111111
fieldset_items = settings.CONFIG_FIELDSETS.items()
112112
else:
113113
fieldset_items = settings.CONFIG_FIELDSETS
114114

115-
context['fieldsets'] = []
115+
context["fieldsets"] = []
116116
for fieldset_title, fieldset_data in fieldset_items:
117117
if isinstance(fieldset_data, dict):
118-
fields_list = fieldset_data['fields']
119-
collapse = fieldset_data.get('collapse', False)
118+
fields_list = fieldset_data["fields"]
119+
collapse = fieldset_data.get("collapse", False)
120120
else:
121121
fields_list = fieldset_data
122122
collapse = False
123123

124124
absent_fields = [field for field in fields_list if field not in settings.CONFIG]
125125
if any(absent_fields):
126126
raise ValueError(
127-
'CONSTANCE_CONFIG_FIELDSETS contains field(s) that does not exist(s): {}'.format(
128-
', '.join(absent_fields)
127+
"CONSTANCE_CONFIG_FIELDSETS contains field(s) that does not exist(s): {}".format(
128+
", ".join(absent_fields)
129129
)
130130
)
131131

@@ -135,16 +135,16 @@ def changelist_view(self, request, extra_context=None):
135135
options = settings.CONFIG.get(name)
136136
if options:
137137
config_values.append(self.get_config_value(name, options, form, initial))
138-
fieldset_context = {'title': fieldset_title, 'config_values': config_values}
138+
fieldset_context = {"title": fieldset_title, "config_values": config_values}
139139

140140
if collapse:
141-
fieldset_context['collapse'] = True
142-
context['fieldsets'].append(fieldset_context)
141+
fieldset_context["collapse"] = True
142+
context["fieldsets"].append(fieldset_context)
143143
if not isinstance(settings.CONFIG_FIELDSETS, (OrderedDict, tuple)):
144-
context['fieldsets'].sort(key=itemgetter('title'))
144+
context["fieldsets"].sort(key=itemgetter("title"))
145145

146146
if not isinstance(settings.CONFIG, OrderedDict):
147-
context['config_values'].sort(key=itemgetter('name'))
147+
context["config_values"].sort(key=itemgetter("name"))
148148
request.current_app = self.admin_site.name
149149
return TemplateResponse(request, self.change_list_template, context)
150150

@@ -162,11 +162,11 @@ def has_change_permission(self, request, obj=None):
162162

163163
class Config:
164164
class Meta:
165-
app_label = 'constance'
166-
object_name = 'Config'
165+
app_label = "constance"
166+
object_name = "Config"
167167
concrete_model = None
168-
model_name = module_name = 'config'
169-
verbose_name_plural = _('config')
168+
model_name = module_name = "config"
169+
verbose_name_plural = _("config")
170170
abstract = False
171171
swapped = False
172172
is_composite_pk = False
@@ -175,19 +175,19 @@ def get_ordered_objects(self):
175175
return False
176176

177177
def get_change_permission(self):
178-
return f'change_{self.model_name}'
178+
return f"change_{self.model_name}"
179179

180180
@property
181181
def app_config(self):
182182
return apps.get_app_config(self.app_label)
183183

184184
@property
185185
def label(self):
186-
return f'{self.app_label}.{self.object_name}'
186+
return f"{self.app_label}.{self.object_name}"
187187

188188
@property
189189
def label_lower(self):
190-
return f'{self.app_label}.{self.model_name}'
190+
return f"{self.app_label}.{self.model_name}"
191191

192192
_meta = Meta()
193193

constance/apps.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66

77

88
class ConstanceConfig(AppConfig):
9-
name = 'constance'
10-
verbose_name = _('Constance')
11-
default_auto_field = 'django.db.models.AutoField'
9+
name = "constance"
10+
verbose_name = _("Constance")
11+
default_auto_field = "django.db.models.AutoField"
1212

1313
def ready(self):
14-
checks.register(check_fieldsets, 'constance')
14+
checks.register(check_fieldsets, "constance")

constance/backends/database.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def __init__(self):
2222
self._model = Constance
2323
self._prefix = settings.DATABASE_PREFIX
2424
self._autofill_timeout = settings.DATABASE_CACHE_AUTOFILL_TIMEOUT
25-
self._autofill_cachekey = 'autofilled'
25+
self._autofill_cachekey = "autofilled"
2626

2727
if self._model._meta.app_config is None:
2828
raise ImproperlyConfigured(
@@ -34,9 +34,9 @@ def __init__(self):
3434
self._cache = caches[settings.DATABASE_CACHE_BACKEND]
3535
if isinstance(self._cache, LocMemCache):
3636
raise ImproperlyConfigured(
37-
'The CONSTANCE_DATABASE_CACHE_BACKEND setting refers to a '
37+
"The CONSTANCE_DATABASE_CACHE_BACKEND setting refers to a "
3838
f"subclass of Django's local-memory backend ({settings.DATABASE_CACHE_BACKEND!r}). Please "
39-
'set it to a backend that supports cross-process caching.'
39+
"set it to a backend that supports cross-process caching."
4040
)
4141
else:
4242
self._cache = None
@@ -45,7 +45,7 @@ def __init__(self):
4545
post_save.connect(self.clear, sender=self._model)
4646

4747
def add_prefix(self, key):
48-
return f'{self._prefix}{key}'
48+
return f"{self._prefix}{key}"
4949

5050
def autofill(self):
5151
if not self._autofill_timeout or not self._cache:
@@ -111,7 +111,7 @@ def set(self, key, value):
111111
if not created:
112112
old_value = loads(constance.value)
113113
constance.value = dumps(value)
114-
constance.save(update_fields=['value'])
114+
constance.save(update_fields=["value"])
115115
else:
116116
old_value = None
117117

constance/backends/redisd.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@ def __init__(self):
2323
try:
2424
import redis
2525
except ImportError:
26-
raise ImproperlyConfigured('The Redis backend requires redis-py to be installed.') from None
26+
raise ImproperlyConfigured("The Redis backend requires redis-py to be installed.") from None
2727
if isinstance(settings.REDIS_CONNECTION, str):
2828
self._rd = redis.from_url(settings.REDIS_CONNECTION)
2929
else:
3030
self._rd = redis.Redis(**settings.REDIS_CONNECTION)
3131

3232
def add_prefix(self, key):
33-
return f'{self._prefix}{key}'
33+
return f"{self._prefix}{key}"
3434

3535
def get(self, key):
3636
value = self._rd.get(self.add_prefix(key))

constance/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ class Config:
66
"""The global config wrapper that handles the backend."""
77

88
def __init__(self):
9-
super().__setattr__('_backend', utils.import_module_attr(settings.BACKEND)())
9+
super().__setattr__("_backend", utils.import_module_attr(settings.BACKEND)())
1010

1111
def __getattr__(self, key):
1212
try:

constance/checks.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,22 @@ def check_fieldsets(*args, **kwargs) -> list[CheckMessage]:
1414

1515
errors = []
1616

17-
if hasattr(settings, 'CONFIG_FIELDSETS') and settings.CONFIG_FIELDSETS:
17+
if hasattr(settings, "CONFIG_FIELDSETS") and settings.CONFIG_FIELDSETS:
1818
missing_keys, extra_keys = get_inconsistent_fieldnames()
1919
if missing_keys:
2020
check = checks.Warning(
21-
_('CONSTANCE_CONFIG_FIELDSETS is missing field(s) that exists in CONSTANCE_CONFIG.'),
22-
hint=', '.join(sorted(missing_keys)),
23-
obj='settings.CONSTANCE_CONFIG',
24-
id='constance.E001',
21+
_("CONSTANCE_CONFIG_FIELDSETS is missing field(s) that exists in CONSTANCE_CONFIG."),
22+
hint=", ".join(sorted(missing_keys)),
23+
obj="settings.CONSTANCE_CONFIG",
24+
id="constance.E001",
2525
)
2626
errors.append(check)
2727
if extra_keys:
2828
check = checks.Warning(
29-
_('CONSTANCE_CONFIG_FIELDSETS contains extra field(s) that does not exist in CONFIG.'),
30-
hint=', '.join(sorted(extra_keys)),
31-
obj='settings.CONSTANCE_CONFIG',
32-
id='constance.E002',
29+
_("CONSTANCE_CONFIG_FIELDSETS contains extra field(s) that does not exist in CONFIG."),
30+
hint=", ".join(sorted(extra_keys)),
31+
obj="settings.CONSTANCE_CONFIG",
32+
id="constance.E002",
3333
)
3434
errors.append(check)
3535
return errors
@@ -53,8 +53,8 @@ def get_inconsistent_fieldnames() -> tuple[set, set]:
5353
for _fieldset_title, fields_list in fieldset_items:
5454
# fields_list can be a dictionary, when a fieldset is defined as collapsible
5555
# https://django-constance.readthedocs.io/en/latest/#fieldsets-collapsing
56-
if isinstance(fields_list, dict) and 'fields' in fields_list:
57-
fields_list = fields_list['fields']
56+
if isinstance(fields_list, dict) and "fields" in fields_list:
57+
fields_list = fields_list["fields"]
5858
unique_field_names.update(fields_list)
5959
if not unique_field_names:
6060
return unique_field_names, unique_field_names

constance/codecs.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
logger = logging.getLogger(__name__)
1616

17-
DEFAULT_DISCRIMINATOR = 'default'
17+
DEFAULT_DISCRIMINATOR = "default"
1818

1919

2020
class JSONEncoder(json.JSONEncoder):
@@ -24,11 +24,11 @@ def default(self, o):
2424
for discriminator, (t, _, encoder) in _codecs.items():
2525
if isinstance(o, t):
2626
return _as(discriminator, encoder(o))
27-
raise TypeError(f'Object of type {o.__class__.__name__} is not JSON serializable')
27+
raise TypeError(f"Object of type {o.__class__.__name__} is not JSON serializable")
2828

2929

3030
def _as(discriminator: str, v: Any) -> dict[str, Any]:
31-
return {'__type__': discriminator, '__value__': v}
31+
return {"__type__": discriminator, "__value__": v}
3232

3333

3434
def dumps(obj, _dumps=json.dumps, cls=JSONEncoder, default_kwargs=None, **kwargs):
@@ -44,7 +44,7 @@ def loads(s, _loads=json.loads, *, first_level=True, **kwargs):
4444
"""Deserialize json string to object."""
4545
if first_level:
4646
return _loads(s, object_hook=object_hook, **kwargs)
47-
if isinstance(s, dict) and '__type__' not in s and '__value__' not in s:
47+
if isinstance(s, dict) and "__type__" not in s and "__value__" not in s:
4848
return {k: loads(v, first_level=False) for k, v in s.items()}
4949
if isinstance(s, list):
5050
return list(loads(v, first_level=False) for v in s)
@@ -53,20 +53,20 @@ def loads(s, _loads=json.loads, *, first_level=True, **kwargs):
5353

5454
def object_hook(o: dict) -> Any:
5555
"""Hook function to perform custom deserialization."""
56-
if o.keys() == {'__type__', '__value__'}:
57-
if o['__type__'] == DEFAULT_DISCRIMINATOR:
58-
return o['__value__']
59-
codec = _codecs.get(o['__type__'])
56+
if o.keys() == {"__type__", "__value__"}:
57+
if o["__type__"] == DEFAULT_DISCRIMINATOR:
58+
return o["__value__"]
59+
codec = _codecs.get(o["__type__"])
6060
if not codec:
61-
raise ValueError(f'Unsupported type: {o["__type__"]}')
62-
return codec[1](o['__value__'])
63-
if '__type__' not in o and '__value__' not in o:
61+
raise ValueError(f"Unsupported type: {o['__type__']}")
62+
return codec[1](o["__value__"])
63+
if "__type__" not in o and "__value__" not in o:
6464
return o
65-
logger.error('Cannot deserialize object: %s', o)
66-
raise ValueError(f'Invalid object: {o}')
65+
logger.error("Cannot deserialize object: %s", o)
66+
raise ValueError(f"Invalid object: {o}")
6767

6868

69-
T = TypeVar('T')
69+
T = TypeVar("T")
7070

7171

7272
class Encoder(Protocol[T]):
@@ -79,9 +79,9 @@ def __call__(self, value: str, /) -> T: ... # pragma: no cover
7979

8080
def register_type(t: type[T], discriminator: str, encoder: Encoder[T], decoder: Decoder[T]):
8181
if not discriminator:
82-
raise ValueError('Discriminator must be specified')
82+
raise ValueError("Discriminator must be specified")
8383
if _codecs.get(discriminator) or discriminator == DEFAULT_DISCRIMINATOR:
84-
raise ValueError(f'Type with discriminator {discriminator} is already registered')
84+
raise ValueError(f"Type with discriminator {discriminator} is already registered")
8585
_codecs[discriminator] = (t, decoder, encoder)
8686

8787

@@ -90,12 +90,12 @@ def register_type(t: type[T], discriminator: str, encoder: Encoder[T], decoder:
9090

9191
def _register_default_types():
9292
# NOTE: datetime should be registered before date, because datetime is also instance of date.
93-
register_type(datetime, 'datetime', datetime.isoformat, datetime.fromisoformat)
94-
register_type(date, 'date', lambda o: o.isoformat(), lambda o: datetime.fromisoformat(o).date())
95-
register_type(time, 'time', lambda o: o.isoformat(), time.fromisoformat)
96-
register_type(Decimal, 'decimal', str, Decimal)
97-
register_type(uuid.UUID, 'uuid', lambda o: o.hex, uuid.UUID)
98-
register_type(timedelta, 'timedelta', lambda o: o.total_seconds(), lambda o: timedelta(seconds=o))
93+
register_type(datetime, "datetime", datetime.isoformat, datetime.fromisoformat)
94+
register_type(date, "date", lambda o: o.isoformat(), lambda o: datetime.fromisoformat(o).date())
95+
register_type(time, "time", lambda o: o.isoformat(), time.fromisoformat)
96+
register_type(Decimal, "decimal", str, Decimal)
97+
register_type(uuid.UUID, "uuid", lambda o: o.hex, uuid.UUID)
98+
register_type(timedelta, "timedelta", lambda o: o.total_seconds(), lambda o: timedelta(seconds=o))
9999

100100

101101
_register_default_types()

0 commit comments

Comments
 (0)