Skip to content

Commit

Permalink
Use Python 3.6+ f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
apragacz committed Dec 28, 2023
1 parent e6421ac commit 25e1b02
Show file tree
Hide file tree
Showing 25 changed files with 48 additions and 103 deletions.
12 changes: 5 additions & 7 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,12 @@

# -- Project information -----------------------------------------------------

project = 'Django REST Registration'
docs_title = '{project} documentation'.format(project=project)
author = 'Andrzej Pragacz'
project = "Django REST Registration"
docs_title = f"{project} documentation"
author = "Andrzej Pragacz"
datetime_now = datetime.datetime.now()
current_year = datetime_now
copyright = '{current_year}, {author}'.format( # noqa: E501 pylint: disable=redefined-builtin
author=author, current_year=current_year)
copyright = f"{current_year}, {author}" # pylint: disable=redefined-builtin
version = rest_registration.__version__
release = version

Expand Down Expand Up @@ -213,8 +212,7 @@
}
settings_fields_groups_map = settings_fields.SETTINGS_FIELDS_GROUPS_MAP
for group_name, settings_fields in settings_fields_groups_map.items():
ctx_key = 'detailed_configuration__{group_name}'.format(
group_name=group_name)
ctx_key = f"detailed_configuration__{group_name}"
jinja_contexts[ctx_key] = {
'settings_fields': settings_fields,
'generate_setting_refs': False,
Expand Down
5 changes: 2 additions & 3 deletions examples/sharedlinks/sharedlinks-backend/links/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Link(models.Model):
)

def __str__(self):
return '{self.title} ({self.url})'.format(self=self)
return f"{self.title} ({self.url})"

def get_num_of_positive_votes(self):
return self.votes.filter(positive=True).count()
Expand Down Expand Up @@ -53,5 +53,4 @@ def __str__(self):
else:
vote = 'neutral'

return '{vote} vote for {self.link} by {self.voter}'.format(
vote=vote, self=self)
return f"{vote} vote for {self.link} by {self.voter}"
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@


def get_frontend_url(uri):
return 'http://localhost:3000{uri}'.format(uri=uri)
return f"http://localhost:3000{uri}"


REST_REGISTRATION = {
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ disable = [
"line-too-long",
"ungrouped-imports",
"fixme",
"consider-using-f-string",
]

[tool.pylint.reports]
Expand Down
6 changes: 3 additions & 3 deletions rest_registration/api/views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ def get_serializer_class(self) -> Type[Serializer]:
(Eg. admins get full serialization, others get basic serialization)
"""
assert self.serializer_class is not None, (
"'%s' should either include a `serializer_class` attribute, "
"or override the `get_serializer_class()` method."
% self.__class__.__name__
f"'{self.__class__.__name__}' should either include a "
f"`serializer_class` attribute, "
f"or override the `get_serializer_class()` method."
)

return self.serializer_class
Expand Down
4 changes: 2 additions & 2 deletions rest_registration/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class ErrorCode(_BaseCheckCodeMixin, Enum):
INVALID_AUTH_BACKENDS_CONFIG = 14

def get_code_id(self) -> str:
return 'E{self.value:03d}'.format(self=self)
return f"E{self.value:03d}"

def get_check_message_class(self) -> Type[CheckMessage]:
return checks.Error
Expand All @@ -46,7 +46,7 @@ class WarningCode(_BaseCheckCodeMixin, Enum):
DEPRECATION = 2

def get_code_id(self) -> str:
return 'W{self.value:03d}'.format(self=self)
return f"W{self.value:03d}"

def get_check_message_class(self) -> Type[CheckMessage]:
return checks.Warning
Expand Down
3 changes: 1 addition & 2 deletions rest_registration/signers/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ def _calculate_salt(self, data):
# implies changed salt used when verifying the input data.
verification_flag_field = get_user_setting('VERIFICATION_FLAG_FIELD')
verification_flag = getattr(user, verification_flag_field)
salt = '{self.SALT_BASE}:{verification_flag}'.format(
self=self, verification_flag=verification_flag)
salt = f"{self.SALT_BASE}:{verification_flag}"
else:
salt = self.SALT_BASE
return salt
3 changes: 1 addition & 2 deletions rest_registration/signers/reset_password.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ def _calculate_salt(self, data):
# was caused by previous password reset and the signature
# is not valid anymore because changed password hash implies
# changed salt used when verifying the input data.
salt = '{self.SALT_BASE}:{user_password_hash}'.format(
self=self, user_password_hash=user_password_hash)
salt = f"{self.SALT_BASE}:{user_password_hash}"
else:
salt = self.SALT_BASE
return salt
5 changes: 2 additions & 3 deletions rest_registration/utils/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class CheckCode:
def get_full_code_id(self) -> str:
app_name = self.get_app_name()
code_id = self.get_code_id()
return '{app_name}.{code_id}'.format(app_name=app_name, code_id=code_id)
return f"{app_name}.{code_id}"

def get_app_name(self) -> str:
raise NotImplementedError()
Expand Down Expand Up @@ -81,8 +81,7 @@ def check_fun(
fun()
except Exception as exc: # pylint: disable=broad-except
exc_str = str(exc)
msg = '{error_message}: {exc_str}'.format(
error_message=error_message, exc_str=exc_str)
msg = f"{error_message}: {exc_str}"
return [
message_cls(
msg,
Expand Down
10 changes: 5 additions & 5 deletions rest_registration/utils/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ def parse_template_config(template_config_data: Dict[str, Any]) -> EmailTemplate
)
else:
raise ImproperlyConfigured(
'Could not parse template config data: {template_config_data}'.format( # noqa: E501
template_config_data=template_config_data))
f"Could not parse template config data: {template_config_data}",
)

_validate_template_name_existence(config.subject_template_name)
_validate_template_name_existence(config.text_body_template_name)
Expand All @@ -109,6 +109,6 @@ def _validate_template_name_existence(template_name: str) -> None:
get_template(template_name)
except TemplateDoesNotExist:
raise ImproperlyConfigured(
'Template {template_name!r} does not exist; ensure that your'
' Django TEMPLATES setting is configured correctly'.format(
template_name=template_name)) from None
f"Template {template_name!r} does not exist; ensure that your"
f" Django TEMPLATES setting is configured correctly",
) from None
5 changes: 2 additions & 3 deletions rest_registration/utils/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def handle_endtag(self, tag: str) -> None:
last_segment = last_paragraph[-1] if last_paragraph else None
if (self._preserve_urls and
tag_info.name == 'a' and href and href != last_segment):
self._append_segment('({href})'.format(href=href))
self._append_segment(f"({href})")

if tag == 'p':
self._paragraphs.append([])
Expand All @@ -58,8 +58,7 @@ def handle_data(self, data: str) -> None:
self._append_segment(data)

def error(self, message: str) -> None:
raise ValueError("HTML parse error: {message}".format(
message=message))
raise ValueError(f"HTML parse error: {message}")

def get_data(self) -> str:
paragraph_texts = []
Expand Down
4 changes: 1 addition & 3 deletions rest_registration/utils/nested_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ def is_default(self, attr: str) -> bool:

def __getattr__(self, attr: str) -> Any:
if attr not in self.defaults.keys():
raise AttributeError(
"Invalid {self.root_setting_name} setting: '{attr}'".format(
self=self, attr=attr))
raise AttributeError(f"Invalid {self.root_setting_name} setting: '{attr}'")

try:
# Check if present in user settings
Expand Down
2 changes: 1 addition & 1 deletion rest_registration/utils/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def get_user_field_obj(name: str) -> 'UserField':


def get_user_setting(name: str) -> Any:
setting_name = 'USER_{name}'.format(name=name)
setting_name = f"USER_{name}"
user_class = get_user_model()
placeholder = object()
value = getattr(user_class, name, placeholder)
Expand Down
2 changes: 1 addition & 1 deletion rest_registration/utils/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def verify_signer_or_bad_request(signer: URLParamsSigner) -> None:
def build_default_verification_url(signer: URLParamsSigner) -> str:
base_url = signer.get_base_url()
params = urlencode(signer.get_signed_data())
url = '{base_url}?{params}'.format(base_url=base_url, params=params)
url = f"{base_url}?{params}"
if signer.request:
url = signer.request.build_absolute_uri(url)
return url
Expand Down
2 changes: 1 addition & 1 deletion tests/doctest_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ def _print_operator_test(first, second, op, fail_message_fmt): # noqa: E501 pyl
first=first,
second=second,
operator=op)
print('FAIL:\n{fail_msg}'.format(fail_msg=fail_msg)) # noqa: T201
print(f"FAIL:\n{fail_msg}") # noqa: T201
9 changes: 2 additions & 7 deletions tests/helpers/api_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,20 +114,15 @@ def _assert_response(
expected_status_code=None):
status_code = response.status_code
if expected_status_code is not None:
msg_format = dedent("""\
msg = dedent(f"""\
Response returned with HTTP code {status_code} but code {expected_status_code} was expected.
Response body was {response.data}.""") # noqa: E501
else:
msg_format = dedent("""\
msg = dedent(f"""\
Response unexpectedly returned with HTTP code {status_code}
Response body was {response.data}.""")
msg = msg_format.format(
status_code=status_code,
expected_status_code=expected_status_code,
response=response,
)
if expected_status_code is not None:
assert status_code == expected_status_code, msg
elif expected_valid_response:
Expand Down
7 changes: 2 additions & 5 deletions tests/helpers/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,14 @@ def create_test_user(**kwargs):


def assert_len_equals(collection, expected_len, msg=None):
std_msg = "{collection} does not have length {expected_len}".format(
collection=collection,
expected_len=expected_len,
)
std_msg = f"{collection} does not have length {expected_len}"
assert len(collection) == expected_len, format_assert_message(msg, std_msg)


def format_assert_message(msg, standard_msg="assertion failed"):
if msg is None:
return standard_msg
return "{standard_msg} : {msg}".format(standard_msg=standard_msg, msg=msg)
return f"{standard_msg} : {msg}"


USER_DEFAULT_FIELD_VALUES = {
Expand Down
6 changes: 1 addition & 5 deletions tests/helpers/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,5 @@ def is_set(self):

def _assert_emails_sent(sent_emails, expected_num):
num_of_sent_emails = len(sent_emails)
msg_format = "Expected {expected_num} emails to be sent, but found {num_of_sent_emails}" # noqa: E501
msg = msg_format.format(
expected_num=expected_num,
num_of_sent_emails=num_of_sent_emails,
)
msg = f"Expected {expected_num} emails to be sent, but found {num_of_sent_emails}"
assert num_of_sent_emails == expected_num, msg
35 changes: 6 additions & 29 deletions tests/helpers/testcases.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,31 +24,17 @@ def create_test_user(self, **kwargs):
return create_test_user(**kwargs)

def assert_len_equals(self, collection, expected_len, msg=None):
std_msg_format = "{collection} does not have length {expected_len}"
std_msg = std_msg_format.format(
collection=collection,
expected_len=expected_len,
)
std_msg = f"{collection} does not have length {expected_len}"
if len(collection) != expected_len:
self.fail(self._formatMessage(msg, std_msg))

def assert_is_between(self, value, start, end, msg=None):
std_msg_format = "{value} is not in range [{start}, {end})"
std_msg = std_msg_format.format(
value=value,
start=start,
end=end,
)
std_msg = f"{value} is not in range [{start}, {end})"
if not start <= value < end:
self.fail(self._formatMessage(msg, std_msg))

def assert_is_not_between(self, value, start, end, msg=None):
std_msg_format = "{value} is unexpectedly in range [{start}, {end})"
std_msg = std_msg_format.format(
value=value,
start=start,
end=end,
)
std_msg = f"{value} is unexpectedly in range [{start}, {end})"
if start <= value < end:
self.fail(self._formatMessage(msg, std_msg))

Expand All @@ -62,11 +48,7 @@ def _assert_mails_sent(self, expected_num):
with self.capture_sent_emails() as sent_emails:
yield sent_emails
num_of_sent_emails = len(sent_emails)
msg_format = "Expected {expected_num} emails to be sent, but found {num_of_sent_emails}" # noqa: E501
msg = msg_format.format(
expected_num=expected_num,
num_of_sent_emails=num_of_sent_emails,
)
msg = f"Expected {expected_num} emails to be sent, but found {num_of_sent_emails}" # noqa: E501
self.assertEqual(num_of_sent_emails, expected_num, msg=msg)

@contextlib.contextmanager
Expand Down Expand Up @@ -98,12 +80,7 @@ def _assert_urls_in_text(self, text, expected_num, line_url_pattern):
match_groupdict = match.groupdict()
urls.append(match_groupdict['url'])
num_of_urls = len(urls)
msg_format = "Found {num_of_urls} urls instead of {expected_num} in:\n{text}" # noqa: E501
msg = msg_format.format(
num_of_urls=num_of_urls,
expected_num=expected_num,
text=text,
)
msg = f"Found {num_of_urls} urls instead of {expected_num} in:\n{text}"
self.assertEqual(num_of_urls, expected_num, msg=msg)
return urls

Expand Down Expand Up @@ -133,7 +110,7 @@ def setUp(self):
def full_view_name(self):
assert self.APP_NAME
assert self.VIEW_NAME
return '{self.APP_NAME}:{self.VIEW_NAME}'.format(self=self)
return f"{self.APP_NAME}:{self.VIEW_NAME}"

@property
def view_url(self):
Expand Down
7 changes: 1 addition & 6 deletions tests/helpers/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,6 @@ def _assert_urls_in_text(text, expected_num, line_url_pattern):
match_groupdict = match.groupdict()
urls.append(match_groupdict['url'])
num_of_urls = len(urls)
msg_format = "Found {num_of_urls} urls instead of {expected_num} in:\n{text}" # noqa: E501
msg = msg_format.format(
num_of_urls=num_of_urls,
expected_num=expected_num,
text=text,
)
msg = f"Found {num_of_urls} urls instead of {expected_num} in:\n{text}"
assert num_of_urls == expected_num, msg
return urls
4 changes: 2 additions & 2 deletions tests/helpers/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ def _parse_verification_url(

for key, values in query.items():
if not values:
raise ValueError("no values for '{key}".format(key=key))
raise ValueError(f"no values for {key!r}")
if len(values) > 1:
raise ValueError("multiple values for '{key}'".format(key=key))
raise ValueError(f"multiple values for {key!r}")

verification_data = {key: values[0] for key, values in query.items()}
return parsed_url.path, verification_data
2 changes: 1 addition & 1 deletion tests/helpers/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def __init__(self, view_name, app_name='rest_registration'):

@property
def full_view_name(self):
return '{self.app_name}:{self.view_name}'.format(self=self)
return f"{self.app_name}:{self.view_name}"

@property
def view_url(self):
Expand Down
10 changes: 3 additions & 7 deletions tests/unit_tests/api/views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,7 @@ def assert_response(
self, response, expected_valid_response=True,
expected_status_code=None):
status_code = response.status_code
msg_format = "Response returned with code {status_code}, body {response.data}" # noqa: E501
msg = msg_format.format(
status_code=status_code,
response=response,
)
msg = f"Response returned with code {status_code}, body {response.data}"
if expected_status_code is not None:
self.assertEqual(status_code, expected_status_code, msg=msg)
elif expected_valid_response:
Expand Down Expand Up @@ -102,9 +98,9 @@ def _parse_verification_url(self, url, verification_field_names):

for key, values in query.items():
if not values:
raise ValueError("no values for '{key}".format(key=key))
raise ValueError(f"no values for {key!r}")
if len(values) > 1:
raise ValueError("multiple values for '{key}'".format(key=key))
raise ValueError(f"multiple values for {key!r}")

verification_data = {key: values[0] for key, values in query.items()}
return parsed_url.path, verification_data
2 changes: 1 addition & 1 deletion tests/unit_tests/api/views/register/test_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def parse_custom_verification_url(url, verification_field_names):
url_path = parsed_url.path.rstrip('/')
url_segments = url_path.rsplit('/', num_of_fields)
if len(url_segments) != num_of_fields + 1:
raise ValueError("Could not parse {url}".format(url=url))
raise ValueError(f"Could not parse {url!r}")

data_segments = url_segments[1:]
url_path = url_segments[0] + '/'
Expand Down
Loading

0 comments on commit 25e1b02

Please sign in to comment.