From ec91456f5d1b33e1f2fb228e03574757b9dd3650 Mon Sep 17 00:00:00 2001 From: Sidney Richards Date: Mon, 6 Jan 2025 22:45:54 +0100 Subject: [PATCH] fixup! fixup! [WIP] pre-commit and ruff --- ruff.toml | 2 + src/open_inwoner/accounts/gateways.py | 4 +- src/open_inwoner/accounts/managers.py | 2 +- src/open_inwoner/accounts/models.py | 6 +- .../accounts/notifications/tasks.py | 3 +- .../tests/test_notify_expiring_actions.py | 2 +- .../accounts/views/contactmoments.py | 3 +- src/open_inwoner/accounts/views/login.py | 8 +- src/open_inwoner/cms/cases/views/cases.py | 2 +- src/open_inwoner/cms/cases/views/services.py | 9 ++- src/open_inwoner/cms/cases/views/status.py | 33 +++++--- .../components/templatetags/string_tags.py | 4 +- src/open_inwoner/conf/base.py | 2 +- src/open_inwoner/conf/local_example.py | 2 +- src/open_inwoner/configurations/admin.py | 9 ++- src/open_inwoner/configurations/models.py | 2 +- src/open_inwoner/openklant/api_models.py | 18 ++--- src/open_inwoner/openklant/services.py | 3 +- .../tests/test_openklant2_service.py | 4 +- src/open_inwoner/openzaak/api_models.py | 78 +++++++++---------- src/open_inwoner/openzaak/clients.py | 5 +- src/open_inwoner/openzaak/exceptions.py | 2 +- src/open_inwoner/openzaak/import_export.py | 5 +- .../openzaak/tests/test_case_detail.py | 6 +- .../openzaak/tests/test_import_export.py | 1 - .../openzaak/tests/test_zgw_imports.py | 2 +- .../tests/test_zgw_imports_iotypes.py | 2 - src/open_inwoner/plans/views.py | 10 +-- src/open_inwoner/questionnaire/admin.py | 8 +- src/open_inwoner/questionnaire/models.py | 2 +- src/open_inwoner/search/results.py | 3 +- src/open_inwoner/ssd/templatetags/ssd_tags.py | 2 +- src/open_inwoner/utils/admin.py | 4 +- src/open_inwoner/utils/decorators.py | 6 +- src/open_inwoner/utils/geocode.py | 2 +- src/open_inwoner/utils/logentry.py | 24 +++++- src/open_inwoner/utils/mixins.py | 6 +- src/open_inwoner/utils/schema.py | 4 +- src/open_inwoner/utils/templatetags/utils.py | 4 +- src/open_inwoner/utils/tests/test_glom.py | 6 +- src/open_inwoner/utils/text.py | 2 +- src/open_inwoner/utils/validators.py | 2 +- src/openklant2/_resources/base.py | 14 +++- src/openklant2/_resources/partij.py | 4 +- src/openklant2/factories/helpers.py | 2 +- src/openklant2/tests/test_partij.py | 1 + .../types/resources/klant_contact.py | 4 +- 47 files changed, 189 insertions(+), 140 deletions(-) diff --git a/ruff.toml b/ruff.toml index c1a2e9bbf9..ac9b9b5c5b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -41,6 +41,8 @@ select = [ "E", # https://docs.astral.sh/ruff/rules/#pyflakes-f "F", + # https://docs.astral.sh/ruff/rules/#isort-i + "I", ] ignore = [ # Whitespace before ':' (conflicts with Black) diff --git a/src/open_inwoner/accounts/gateways.py b/src/open_inwoner/accounts/gateways.py index 41d729832b..0aa9f03918 100644 --- a/src/open_inwoner/accounts/gateways.py +++ b/src/open_inwoner/accounts/gateways.py @@ -65,7 +65,9 @@ def send(self, to, token, **kwargs): ) except messagebird.client.ErrorException as e: for error in e.errors: - logger.critical(f"Could not send SMS to {to}:\n{error}") + logger.critical( + ("Could not send SMS to {to}:\n{error}").format(to=to, error=error) + ) raise GatewayError() else: logging.debug('Sent SMS to %s: "%s"', to, self.get_message(token)) diff --git a/src/open_inwoner/accounts/managers.py b/src/open_inwoner/accounts/managers.py index e752a10aa4..c34eea1965 100644 --- a/src/open_inwoner/accounts/managers.py +++ b/src/open_inwoner/accounts/managers.py @@ -33,7 +33,7 @@ def get_by_kvk(self, kvk): def eherkenning_create(self, kvk, **kwargs): return super().create( - email=f"user-{kvk}@localhost", + email="user-{}@localhost".format(kvk), login_type=LoginTypeChoices.eherkenning, kvk=kvk, ) diff --git a/src/open_inwoner/accounts/models.py b/src/open_inwoner/accounts/models.py index 10ae22f7df..2ba955132e 100644 --- a/src/open_inwoner/accounts/models.py +++ b/src/open_inwoner/accounts/models.py @@ -110,7 +110,9 @@ def get_callback_view(self): def generate_uuid_image_name(instance, filename): filename, file_extension = os.path.splitext(filename) - return f"profile/{uuid4()}{file_extension.lower()}" + return "profile/{uuid}{file_extension}".format( + uuid=uuid4(), file_extension=file_extension.lower() + ) class User(AbstractBaseUser, PermissionsMixin): @@ -881,7 +883,7 @@ def get_full_name(self): """ Returns the first_name plus the last_name of the invitee, with a space in between. """ - full_name = f"{self.invitee_first_name} {self.invitee_last_name}" + full_name = "{} {}".format(self.invitee_first_name, self.invitee_last_name) return full_name.strip() def save(self, **kwargs): diff --git a/src/open_inwoner/accounts/notifications/tasks.py b/src/open_inwoner/accounts/notifications/tasks.py index dbf22924b9..c203b91896 100644 --- a/src/open_inwoner/accounts/notifications/tasks.py +++ b/src/open_inwoner/accounts/notifications/tasks.py @@ -1,5 +1,4 @@ -from collections.abc import Callable -from typing import Any +from typing import Any, Callable import celery diff --git a/src/open_inwoner/accounts/tests/test_notify_expiring_actions.py b/src/open_inwoner/accounts/tests/test_notify_expiring_actions.py index 5e2709dfdb..af5a3dc1af 100644 --- a/src/open_inwoner/accounts/tests/test_notify_expiring_actions.py +++ b/src/open_inwoner/accounts/tests/test_notify_expiring_actions.py @@ -30,7 +30,7 @@ def test_send_emails_about_expiring_actions(self): email1, email2 = mail.outbox - for email, recipient in zip([email1, email2], [joe, schmoe], strict=False): + for email, recipient in zip([email1, email2], [joe, schmoe]): self.assertEqual( email.subject, "Acties verlopen vandaag op Open Inwoner Platform" ) diff --git a/src/open_inwoner/accounts/views/contactmoments.py b/src/open_inwoner/accounts/views/contactmoments.py index 78a5971f83..de47e522a9 100644 --- a/src/open_inwoner/accounts/views/contactmoments.py +++ b/src/open_inwoner/accounts/views/contactmoments.py @@ -1,6 +1,5 @@ import logging -from collections.abc import Iterable -from typing import Protocol +from typing import Iterable, Protocol from django.contrib.auth.mixins import AccessMixin from django.core.exceptions import ImproperlyConfigured diff --git a/src/open_inwoner/accounts/views/login.py b/src/open_inwoner/accounts/views/login.py index d70625bf5d..b52a9bfeb7 100644 --- a/src/open_inwoner/accounts/views/login.py +++ b/src/open_inwoner/accounts/views/login.py @@ -83,7 +83,7 @@ def form_valid(self, form): else: self.log_user_action( user, - f"SMS bericht met code is verzonden aan {user.phonenumber}", + "SMS bericht met code is verzonden aan {}".format(user.phonenumber), ) messages.debug(self.request, gateway.get_message(token)) @@ -255,7 +255,7 @@ def post(self, request): else: self.log_user_action( user, - f"SMS bericht met code is verzonden aan {user.phonenumber}", + "SMS bericht met code is verzonden aan {}".format(user.phonenumber), ) messages.debug(self.request, gateway.get_message(token)) @@ -333,7 +333,7 @@ def render_next_step(self, form, **kwargs): self.log_user_action( self.user_cache, - f"SMS bericht met code is verzonden aan {phonenumber}", + "SMS bericht met code is verzonden aan {}".format(phonenumber), ) return super().render_next_step(form, **kwargs) @@ -345,7 +345,7 @@ def done(self, form_list, **kwargs): self.request.user = self.user_cache self.log_change( self.user_cache, - f"Telefoonnummer gewijzigd: {phonenumber}", + "Telefoonnummer gewijzigd: {}".format(phonenumber), ) self.user_cache.save() diff --git a/src/open_inwoner/cms/cases/views/cases.py b/src/open_inwoner/cms/cases/views/cases.py index 2a6572b538..da30e9ee40 100644 --- a/src/open_inwoner/cms/cases/views/cases.py +++ b/src/open_inwoner/cms/cases/views/cases.py @@ -1,5 +1,5 @@ import logging -from collections.abc import Sequence +from typing import Sequence from django.urls import reverse from django.utils.functional import cached_property diff --git a/src/open_inwoner/cms/cases/views/services.py b/src/open_inwoner/cms/cases/views/services.py index 49aeba8476..7de2b4df64 100644 --- a/src/open_inwoner/cms/cases/views/services.py +++ b/src/open_inwoner/cms/cases/views/services.py @@ -2,9 +2,8 @@ import enum import functools import logging -from collections.abc import Callable from dataclasses import dataclass -from typing import TypedDict +from typing import Callable, TypedDict from django.http import HttpRequest from django.utils.translation import gettext_lazy as _ @@ -226,7 +225,9 @@ def resolve_cases( case = futures[task]["case"] group = futures[task]["api_group"] logger.exception( - f"Error while resolving case {case} with API group {group}" + "Error while resolving case {case} with API group {group}".format( + case=case, group=group + ) ) return resolved_cases @@ -264,7 +265,7 @@ def resolve_case(self, case: Zaak, group: ZGWApiGroupConfig) -> Zaak: ): try: update_case = task.result() - if callable(update_case): + if hasattr(update_case, "__call__"): update_case(case) except BaseException: logger.exception("Error in resolving case", stack_info=True) diff --git a/src/open_inwoner/cms/cases/views/status.py b/src/open_inwoner/cms/cases/views/status.py index c175469c5c..b35bddef71 100644 --- a/src/open_inwoner/cms/cases/views/status.py +++ b/src/open_inwoner/cms/cases/views/status.py @@ -2,9 +2,8 @@ import datetime as dt import logging from collections import defaultdict -from collections.abc import Iterable from datetime import datetime -from typing import Protocol +from typing import Iterable, Protocol from django.conf import settings from django.contrib import messages @@ -317,7 +316,7 @@ def get_second_status_preview(self, statustypen: list) -> StatusType | None: # only 1 statustype for `self.case` # (this scenario is blocked by openzaak, but not part of the zgw standard) if len(statustype_numbers) < 2: - logger.info(f"Case {self.case} has only one statustype") + logger.info("Case {case} has only one statustype".format(case=self.case)) return statustype_numbers.sort() @@ -367,7 +366,9 @@ def sync_statuses_with_status_types( # Workaround: OIP requests the current zaak.status individually and adds the retrieved information to the statustype mapping logger.info( - f"Issue #2037 -- Retrieving status individually for case {self.case.identification} because of eSuite" + "Issue #2037 -- Retrieving status individually for case {} because of eSuite".format( + self.case.identification + ) ) self.case.status = zaken_client.fetch_single_status(self.case.status) status_types_mapping[self.case.status.statustype].append(self.case.status) @@ -458,7 +459,9 @@ def is_file_upload_enabled_for_case_type(self) -> bool: ).exists() ) logger.info( - f"Case {self.case.url} has case type file upload: {case_upload_enabled}" + "Case {url} has case type file upload: {case_upload_enabled}".format( + url=self.case.url, case_upload_enabled=case_upload_enabled + ) ) return case_upload_enabled @@ -471,18 +474,26 @@ def is_file_upload_enabled_for_statustype(self) -> bool: except AttributeError as e: logger.exception(e) logger.info( - f"Could not retrieve status type for case {self.case}; " - "the status has not been resolved to a ZGW model object." + "Could not retrieve status type for case {case}; " + "the status has not been resolved to a ZGW model object.".format( + case=self.case + ) ) return True except KeyError as e: logger.exception(e) logger.info( - f"Could not retrieve status type config for url {self.case.status.statustype.url}" + "Could not retrieve status type config for url {url}".format( + url=self.case.status.statustype.url + ) ) return True logger.info( - f"Case {self.case.url} status type {self.case.status.statustype} has status type file upload: {enabled_for_status_type}" + "Case {url} status type {status_type} has status type file upload: {enabled_for_status_type}".format( + url=self.case.url, + status_type=self.case.status.statustype, + enabled_for_status_type=enabled_for_status_type, + ) ) return enabled_for_status_type @@ -652,9 +663,7 @@ def get_case_document_files( config = OpenZaakConfig.get_solo() documents = [] - for case_info_obj, info_obj in zip( - case_info_objects, info_objects, strict=False - ): + for case_info_obj, info_obj in zip(case_info_objects, info_objects): if not info_obj: continue if not is_info_object_visible( diff --git a/src/open_inwoner/components/templatetags/string_tags.py b/src/open_inwoner/components/templatetags/string_tags.py index 09948c31b1..5662f1c87f 100644 --- a/src/open_inwoner/components/templatetags/string_tags.py +++ b/src/open_inwoner/components/templatetags/string_tags.py @@ -25,7 +25,9 @@ def optional_paragraph(optional_text: str) -> str: if not optional_text: return "" return format_html( - f'

{linebreaksbr(optional_text)}

' + '

{optional_text}

'.format( + optional_text=linebreaksbr(optional_text) + ) ) diff --git a/src/open_inwoner/conf/base.py b/src/open_inwoner/conf/base.py index aa1223445e..580f33bd22 100644 --- a/src/open_inwoner/conf/base.py +++ b/src/open_inwoner/conf/base.py @@ -994,7 +994,7 @@ ) if ALLOWED_HOSTS: - BASE_URL = f"https://{ALLOWED_HOSTS[0]}" + BASE_URL = "https://{}".format(ALLOWED_HOSTS[0]) else: BASE_URL = "https://example.com" diff --git a/src/open_inwoner/conf/local_example.py b/src/open_inwoner/conf/local_example.py index 752855a406..15dea5dcdb 100644 --- a/src/open_inwoner/conf/local_example.py +++ b/src/open_inwoner/conf/local_example.py @@ -17,7 +17,7 @@ PLAYWRIGHT_MULTI_ONLY_DEFAULT = True # Enable django-debug-toolbar -from .dev import INSTALLED_APPS, MIDDLEWARE # noqa: E402 +from .dev import INSTALLED_APPS, MIDDLEWARE INSTALLED_APPS += ["debug_toolbar"] MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] diff --git a/src/open_inwoner/configurations/admin.py b/src/open_inwoner/configurations/admin.py index a589b7344e..41b86c9c44 100644 --- a/src/open_inwoner/configurations/admin.py +++ b/src/open_inwoner/configurations/admin.py @@ -339,7 +339,14 @@ def report_contrast_ratio(self, request, obj): def check_contrast_ratio(label1, color1, label2, color2, expected_ratio): ratio = get_contrast_ratio(color1, color2) if ratio < expected_ratio: - message = f"'{label1}' ({color1}) en '{label2}' ({color2}) hebben niet genoeg contrast: {round(ratio, 1)}:1 waar {expected_ratio}:1 wordt verwacht." + message = "'{label1}' ({color1}) en '{label2}' ({color2}) hebben niet genoeg contrast: {ratio}:1 waar {expected}:1 wordt verwacht.".format( + label1=label1, + color1=color1, + label2=label2, + color2=color2, + ratio=round(ratio, 1), + expected=expected_ratio, + ) self.message_user(request, message, messages.WARNING) check_contrast_ratio( diff --git a/src/open_inwoner/configurations/models.py b/src/open_inwoner/configurations/models.py index eacc223f50..47e3d974c2 100644 --- a/src/open_inwoner/configurations/models.py +++ b/src/open_inwoner/configurations/models.py @@ -702,7 +702,7 @@ class CustomFontSet(models.Model): def update_filename(self, filename: str, new_name: str, path: str) -> str: ext = filename.split(".")[1] filename = f"{new_name}.{ext}" - return f"{path}/{filename}" + return "{path}/{filename}".format(path=path, filename=filename) def update_filename_body(self, filename: str) -> str: return CustomFontSet.update_filename( diff --git a/src/open_inwoner/openklant/api_models.py b/src/open_inwoner/openklant/api_models.py index b2dc137b6c..58c0803895 100644 --- a/src/open_inwoner/openklant/api_models.py +++ b/src/open_inwoner/openklant/api_models.py @@ -1,7 +1,7 @@ import dataclasses from dataclasses import dataclass from datetime import datetime -from typing import NotRequired, TypedDict +from typing import NotRequired, Optional, TypedDict, Union from zgw_consumers.api_models.base import ZGWModel @@ -63,11 +63,11 @@ class ContactMoment(ZGWModel): # eSuite OAS (compatible) url: str bronorganisatie: str - registratiedatum: datetime | None = None + registratiedatum: Optional[datetime] = None kanaal: str = "" tekst: str = "" # NOTE annoyingly we can't put MedewerkerIdentificatie here as type because of - medewerker_identificatie: dict | None = None + medewerker_identificatie: Optional[dict] = None # modification to API for eSuite usefulness *AFWIJKING* identificatie: str = "" @@ -79,8 +79,8 @@ class ContactMoment(ZGWModel): # open-klant OAS voorkeurskanaal: str = "" voorkeurstaal: str = "" - vorig_contactmoment: str | None = None - volgend_contactmoment: str | None = None + vorig_contactmoment: Optional[str] = None + volgend_contactmoment: Optional[str] = None onderwerp_links: list[str] = dataclasses.field(default_factory=list) initiatiefnemer: str = "" @@ -124,8 +124,8 @@ class KlantContactMoment(ZGWModel): # eSuite OAS (compatible) url: str - contactmoment: str | ContactMoment - klant: str | Klant + contactmoment: Union[str, ContactMoment] + klant: Union[str, Klant] rol: str # open-klant non-standard *AFWIJKING* @@ -138,6 +138,6 @@ class ObjectContactMoment(ZGWModel): Contactmomenten API """ - contactmoment: str | ContactMoment - object: str | Klant + contactmoment: Union[str, ContactMoment] + object: Union[str, Klant] object_type: str diff --git a/src/open_inwoner/openklant/services.py b/src/open_inwoner/openklant/services.py index d93f2a6eba..0badc29f95 100644 --- a/src/open_inwoner/openklant/services.py +++ b/src/open_inwoner/openklant/services.py @@ -1,9 +1,8 @@ import datetime import logging import uuid -from collections.abc import Iterable from datetime import timedelta -from typing import Literal, NotRequired, Protocol, Self +from typing import Iterable, Literal, NotRequired, Protocol, Self import glom from ape_pie.client import APIClient diff --git a/src/open_inwoner/openklant/tests/test_openklant2_service.py b/src/open_inwoner/openklant/tests/test_openklant2_service.py index 274df7d5df..820d618326 100644 --- a/src/open_inwoner/openklant/tests/test_openklant2_service.py +++ b/src/open_inwoner/openklant/tests/test_openklant2_service.py @@ -304,7 +304,9 @@ def test_update_partij_from_user(self): ) -QUESTION_DATE = datetime.datetime(2024, 10, 2, 14, 0, 25, 587564, tzinfo=datetime.UTC) +QUESTION_DATE = datetime.datetime( + 2024, 10, 2, 14, 0, 25, 587564, tzinfo=datetime.timezone.utc +) @tag("openklant2") diff --git a/src/open_inwoner/openzaak/api_models.py b/src/open_inwoner/openzaak/api_models.py index a011112d9e..d0506da7cb 100644 --- a/src/open_inwoner/openzaak/api_models.py +++ b/src/open_inwoner/openzaak/api_models.py @@ -2,7 +2,7 @@ import re from dataclasses import dataclass, field from datetime import date, datetime -from typing import Union +from typing import Optional, Union from dateutil.relativedelta import relativedelta from django.utils.translation import gettext as _ @@ -31,12 +31,12 @@ class Zaak(ZGWModel): registratiedatum: date startdatum: date vertrouwelijkheidaanduiding: str - status: Union[str, "Status"] | None - einddatum_gepland: date | None = None - uiterlijke_einddatum_afdoening: date | None = None + status: Optional[Union[str, "Status"]] + einddatum_gepland: Optional[date] = None + uiterlijke_einddatum_afdoening: Optional[date] = None # publicatiedatum: Optional[date] - einddatum: date | None = None - resultaat: Union[str, "Resultaat"] | None = None + einddatum: Optional[date] = None + resultaat: Optional[Union[str, "Resultaat"]] = None # relevante_andere_zaken: list # zaakgeometrie: dict @@ -154,21 +154,21 @@ class ZaakType(ZGWModel): # roltypen: list # besluittypen: list - begin_geldigheid: date | None = None - einde_geldigheid: date | None = None - versiedatum: date | None = None - concept: bool | None = None + begin_geldigheid: Optional[date] = None + einde_geldigheid: Optional[date] = None + versiedatum: Optional[date] = None + concept: Optional[bool] = None @dataclass class ZaakInformatieObject(ZGWModel): url: str informatieobject: Union[str, "InformatieObject"] - zaak: str | Zaak + zaak: Union[str, Zaak] # aard_relatie_weergave: str titel: str # beschrijving: str - registratiedatum: datetime | None + registratiedatum: Optional[datetime] @dataclass @@ -177,8 +177,8 @@ class InformatieObjectType(ZGWModel): catalogus: str omschrijving: str vertrouwelijkheidaanduiding: str - begin_geldigheid: date | None = None - einde_geldigheid: date | None = None + begin_geldigheid: Optional[date] = None + einde_geldigheid: Optional[date] = None concept: bool = False @@ -200,15 +200,15 @@ class InformatieObject(ZGWModel): inhoud: str bestandsomvang: int # indicatieGebruiksrecht: str - informatieobjecttype: str | InformatieObjectType + informatieobjecttype: Union[str, InformatieObjectType] locked: bool # bestandsdelen: List[str] - beschrijving: str | None = "" - link: str | None = "" - ontvangstdatum: str | None = "" - verzenddatum: str | None = "" - ondertekening: dict | None = None # {'soort': '', 'datum': None} - integriteit: dict | None = None # {'algoritme': '', 'waarde': '', 'datum': None} + beschrijving: Optional[str] = "" + link: Optional[str] = "" + ontvangstdatum: Optional[str] = "" + verzenddatum: Optional[str] = "" + ondertekening: Optional[dict] = None # {'soort': '', 'datum': None} + integriteit: Optional[dict] = None # {'algoritme': '', 'waarde': '', 'datum': None} @dataclass @@ -224,14 +224,14 @@ class Rol(ZGWModel): url: str zaak: str betrokkene_type: str - roltype: str | RolType + roltype: Union[str, RolType] omschrijving: str omschrijving_generiek: str roltoelichting: str - indicatie_machtiging: str | None = "" - registratiedatum: datetime | None = None - betrokkene: str | None = "" - betrokkene_identificatie: dict | None = None + indicatie_machtiging: Optional[str] = "" + registratiedatum: Optional[datetime] = None + betrokkene: Optional[str] = "" + betrokkene_identificatie: Optional[dict] = None def get_betrokkene_type_display(self): return RolTypes[self.betrokkene_type].label @@ -251,8 +251,8 @@ class ResultaatType(ZGWModel): omschrijving_generiek: str = "" toelichting: str = "" archiefnominatie: str = "" - archiefactietermijn: relativedelta | None = None - brondatum_archiefprocedure: dict | None = None + archiefactietermijn: Optional[relativedelta] = None + brondatum_archiefprocedure: Optional[dict] = None # E-suite compatibility # result description ("omschrijving") with >20 chars @@ -262,9 +262,9 @@ class ResultaatType(ZGWModel): @dataclass class Resultaat(ZGWModel): url: str - zaak: str | Zaak - resultaattype: str | ResultaatType - toelichting: str | None = "" + zaak: Union[str, Zaak] + resultaattype: Union[str, ResultaatType] + toelichting: Optional[str] = "" @dataclass @@ -272,21 +272,21 @@ class StatusType(ZGWModel): url: str # bug: not required according to OAS zaaktype: str omschrijving: str - volgnummer: int | None # not in eSuite + volgnummer: Optional[int] # not in eSuite omschrijving_generiek: str = "" statustekst: str = "" is_eindstatus: bool = False # not in eSuite - informeren: bool | None = False + informeren: Optional[bool] = False @dataclass class Status(ZGWModel): url: str - zaak: str | Zaak - statustype: str | StatusType - datum_status_gezet: datetime | None = None - statustoelichting: str | None = "" + zaak: Union[str, Zaak] + statustype: Union[str, StatusType] + datum_status_gezet: Optional[datetime] = None + statustoelichting: Optional[str] = "" @dataclass @@ -324,8 +324,8 @@ class OpenSubmission(Model): uuid: str naam: str datum_laatste_wijziging: datetime - vervolg_link: str | None = None - eind_datum_geldigheid: datetime | None = None + vervolg_link: Optional[str] = None + eind_datum_geldigheid: Optional[datetime] = None @property def identification(self) -> str: diff --git a/src/open_inwoner/openzaak/clients.py b/src/open_inwoner/openzaak/clients.py index 86c877d7d1..d880c1051d 100644 --- a/src/open_inwoner/openzaak/clients.py +++ b/src/open_inwoner/openzaak/clients.py @@ -2,10 +2,9 @@ import concurrent.futures import logging import warnings -from collections.abc import Mapping from dataclasses import dataclass from datetime import date -from typing import Any, Literal, TypeAlias, TypeVar +from typing import Any, Literal, Mapping, Type, TypeAlias, TypeVar from ape_pie.client import APIClient from django.conf import settings @@ -883,7 +882,7 @@ def wrapper(*args, **kwargs): def build_zgw_client_from_service(service: Service) -> ZgwClientFactoryReturn: - services_to_client_mapping: Mapping[str, type[ZgwClientFactoryReturn]] = { + services_to_client_mapping: Mapping[str, Type[ZgwClientFactoryReturn]] = { APITypes.zrc: ZakenClient, APITypes.ztc: CatalogiClient, APITypes.drc: DocumentenClient, diff --git a/src/open_inwoner/openzaak/exceptions.py b/src/open_inwoner/openzaak/exceptions.py index 00e6e5904e..ff20d4b4f5 100644 --- a/src/open_inwoner/openzaak/exceptions.py +++ b/src/open_inwoner/openzaak/exceptions.py @@ -1,4 +1,4 @@ -from collections.abc import Sequence +from typing import Sequence class InvalidAuth(Exception): diff --git a/src/open_inwoner/openzaak/import_export.py b/src/open_inwoner/openzaak/import_export.py index 02d30098a1..6fbcc7a2cf 100644 --- a/src/open_inwoner/openzaak/import_export.py +++ b/src/open_inwoner/openzaak/import_export.py @@ -3,8 +3,7 @@ import json import logging from collections import defaultdict -from collections.abc import Generator -from typing import IO, Any, Self +from typing import IO, Any, Generator, Self from urllib.parse import urlparse from django.apps import apps @@ -184,7 +183,7 @@ def __iter__(self) -> Generator[QuerySet, Any, None]: ) def __eq__(self, other: QuerySet) -> bool: - for a, b in zip(self, other, strict=False): + for a, b in zip(self, other): if a.difference(b).exists(): return False return True diff --git a/src/open_inwoner/openzaak/tests/test_case_detail.py b/src/open_inwoner/openzaak/tests/test_case_detail.py index 0071a75850..969b8cb9a8 100644 --- a/src/open_inwoner/openzaak/tests/test_case_detail.py +++ b/src/open_inwoner/openzaak/tests/test_case_detail.py @@ -1030,7 +1030,7 @@ def test_status_is_retrieved_when_user_logged_in_via_digid( links = doc.find(".contactmomenten__link") self.assertEqual(len(links), 3) - for link, question in zip(links, case["questions"], strict=False): + for link, question in zip(links, case["questions"]): self.assertEqual( link.attrib["href"], reverse( @@ -1152,7 +1152,7 @@ def test_pass_endstatus_type_data_if_endstatus_not_reached( self.assertEqual(len(links), 4) - for link, question in zip(links, case["questions"], strict=False): + for link, question in zip(links, case["questions"]): self.assertEqual( link.attrib["href"], reverse( @@ -1701,7 +1701,7 @@ def test_access_as_vestiging_when_only_role_for_vestiging(self, m): response = self.client.get(self.case_detail_url) - self.assertEqual(response.status_code, 200) + self.assertEquals(response.status_code, 200) self.assertContains(response, self.zaak["identificatie"]) @set_kvk_branch_number_in_session("1234") diff --git a/src/open_inwoner/openzaak/tests/test_import_export.py b/src/open_inwoner/openzaak/tests/test_import_export.py index e6a0462d02..31e9df5fac 100644 --- a/src/open_inwoner/openzaak/tests/test_import_export.py +++ b/src/open_inwoner/openzaak/tests/test_import_export.py @@ -137,7 +137,6 @@ def test_only_models_related_to_exported_catalogus_config_are_included(self): "ztc_resultaat", "ztiotc", ), - strict=False, ): with self.subTest( f"{mock_field} should not be in the export's {export_field} field" diff --git a/src/open_inwoner/openzaak/tests/test_zgw_imports.py b/src/open_inwoner/openzaak/tests/test_zgw_imports.py index e6eb4f923f..06cdff68d9 100644 --- a/src/open_inwoner/openzaak/tests/test_zgw_imports.py +++ b/src/open_inwoner/openzaak/tests/test_zgw_imports.py @@ -218,7 +218,7 @@ def test_import_zaaktype_configs_with_catalogs(self, m): ) # check we linked correctly - for i, root in zip((0, 2), self.roots, strict=False): + for i, root in zip((0, 2), self.roots): self.assertEqual(res[i + 0].catalogus, cat_configs[root]["AAA"]) self.assertEqual(res[i + 1].catalogus, cat_configs[root]["BBB"]) diff --git a/src/open_inwoner/openzaak/tests/test_zgw_imports_iotypes.py b/src/open_inwoner/openzaak/tests/test_zgw_imports_iotypes.py index 0d4c407316..b7852e942b 100644 --- a/src/open_inwoner/openzaak/tests/test_zgw_imports_iotypes.py +++ b/src/open_inwoner/openzaak/tests/test_zgw_imports_iotypes.py @@ -318,7 +318,6 @@ def test_import_zaaktype_informatieobjecttype_configs_with_catalog(self, m): for root, root_offset in zip( self.roots, (0, 2), - strict=False, ): # first ZaakTypeConfig has two ZaakTypes and two InfoObjectTypes ztc, ztiotcs = res[root_offset] @@ -420,7 +419,6 @@ def test_import_zaaktype_informatieobjecttype_configs_with_catalog(self, m): for root, root_offset in zip( self.roots, (0, 1), - strict=False, ): self.assertEqual( catalog_and_zaak_type[root][ diff --git a/src/open_inwoner/plans/views.py b/src/open_inwoner/plans/views.py index a83e8d1e4d..7c6c704c70 100644 --- a/src/open_inwoner/plans/views.py +++ b/src/open_inwoner/plans/views.py @@ -434,7 +434,7 @@ def get_object(self): return Plan.objects.connected(self.request.user).get( uuid=self.kwargs.get("uuid") ) - except ObjectDoesNotExist: + except ObjectDoesNotExist as e: raise Http404 def form_valid(self, form): @@ -485,7 +485,7 @@ def get_plan(self): return Plan.objects.connected(self.request.user).get( uuid=self.kwargs.get("plan_uuid") ) - except ObjectDoesNotExist: + except ObjectDoesNotExist as e: raise Http404 def form_valid(self, form): @@ -519,7 +519,7 @@ def get_plan(self): return Plan.objects.connected(self.request.user).get( uuid=self.kwargs.get("plan_uuid") ) - except ObjectDoesNotExist: + except ObjectDoesNotExist as e: raise Http404 def get_template_tag_args(self, context): @@ -534,7 +534,7 @@ def get_plan(self): return Plan.objects.connected(self.request.user).get( uuid=self.kwargs.get("plan_uuid") ) - except ObjectDoesNotExist: + except ObjectDoesNotExist as e: raise Http404 def get_success_url(self) -> str: @@ -577,7 +577,7 @@ def get_plan(self): return Plan.objects.connected(self.request.user).get( uuid=self.kwargs.get("plan_uuid") ) - except ObjectDoesNotExist: + except ObjectDoesNotExist as e: raise Http404 diff --git a/src/open_inwoner/questionnaire/admin.py b/src/open_inwoner/questionnaire/admin.py index 0f800e9325..3449e6bc54 100644 --- a/src/open_inwoner/questionnaire/admin.py +++ b/src/open_inwoner/questionnaire/admin.py @@ -103,14 +103,14 @@ class QuestionnaireStepAdmin(TreeAdmin): def display_question_answer(self, obj): redirect = "" if obj.redirect_to: - redirect = ( - f" - doorsturen -> {obj.redirect_to.question} - {obj.redirect_to.id}" + redirect = " - doorsturen -> {} - {}".format( + obj.redirect_to.question, obj.redirect_to.id ) - postfix = f" ({obj.id} - {obj.code}{redirect})" + postfix = " ({} - {}{})".format(obj.id, obj.code, redirect) if not obj.parent_answer: return obj.question + postfix - return f"{obj.parent_answer} -> {obj.question}" + postfix + return "{} -> {}".format(obj.parent_answer, obj.question) + postfix display_question_answer.allow_tags = True diff --git a/src/open_inwoner/questionnaire/models.py b/src/open_inwoner/questionnaire/models.py index a61006f114..cf7b91c4a4 100644 --- a/src/open_inwoner/questionnaire/models.py +++ b/src/open_inwoner/questionnaire/models.py @@ -109,7 +109,7 @@ class Meta: ordering = ("path",) def __str__(self) -> str: - return f"({self.id} - {self.code}) {self.question}" + return "({} - {}) {}".format(self.id, self.code, self.question) def get_absolute_url(self) -> str: if self.is_root(): diff --git a/src/open_inwoner/search/results.py b/src/open_inwoner/search/results.py index 26b249a5b4..f9a7298e91 100644 --- a/src/open_inwoner/search/results.py +++ b/src/open_inwoner/search/results.py @@ -1,6 +1,7 @@ from collections import OrderedDict from dataclasses import dataclass from operator import attrgetter +from typing import Type from django.db import models from elasticsearch_dsl import FacetedResponse @@ -27,7 +28,7 @@ def label(self) -> str: class Facet: name: str buckets: list[FacetBucket] - model: type[models.Model] + model: Type[models.Model] def __init__(self, name: str, buckets: list, model: models.Model): self.name = name diff --git a/src/open_inwoner/ssd/templatetags/ssd_tags.py b/src/open_inwoner/ssd/templatetags/ssd_tags.py index 0b8445989c..64e85d3a65 100644 --- a/src/open_inwoner/ssd/templatetags/ssd_tags.py +++ b/src/open_inwoner/ssd/templatetags/ssd_tags.py @@ -43,7 +43,7 @@ def format_currency(value: str) -> str: return "0,00" try: - return f"{float(value) / 100:.2f}".replace(".", ",") + return "{:.2f}".format(float(value) / 100).replace(".", ",") except ValueError: return "" diff --git a/src/open_inwoner/utils/admin.py b/src/open_inwoner/utils/admin.py index 2809321495..45df3a890e 100644 --- a/src/open_inwoner/utils/admin.py +++ b/src/open_inwoner/utils/admin.py @@ -120,7 +120,9 @@ def object_link(self, obj): ct = obj.content_type try: url = reverse( - (f"admin:{ct.app_label}_{ct.model}_change"), + ("admin:{app_label}_{model}_change").format( + app_label=ct.app_label, model=ct.model + ), args=[obj.object_id], ) link = format_html( diff --git a/src/open_inwoner/utils/decorators.py b/src/open_inwoner/utils/decorators.py index 249cbedfde..593787e913 100644 --- a/src/open_inwoner/utils/decorators.py +++ b/src/open_inwoner/utils/decorators.py @@ -80,16 +80,14 @@ def decorator(func: Callable[..., RT]) -> Callable[..., RT]: if argspec.defaults: positional_count = len(argspec.args) - len(argspec.defaults) - defaults = dict( - zip(argspec.args[positional_count:], argspec.defaults, strict=False) - ) + defaults = dict(zip(argspec.args[positional_count:], argspec.defaults)) else: defaults = {} @wraps(func) def wrapped(*args, **kwargs) -> RT: key_kwargs = defaults.copy() - named_args = dict(zip(argspec.args, args, strict=False), **kwargs) + named_args = dict(zip(argspec.args, args), **kwargs) key_kwargs.update(**named_args) if argspec.varkw: diff --git a/src/open_inwoner/utils/geocode.py b/src/open_inwoner/utils/geocode.py index c1f06da923..cc6b48205a 100644 --- a/src/open_inwoner/utils/geocode.py +++ b/src/open_inwoner/utils/geocode.py @@ -39,7 +39,7 @@ def __init__( ) self.domain = domain.strip("/") - self.api = f"{self.scheme}://{self.domain}{self.geocode_path}" + self.api = "{}://{}{}".format(self.scheme, self.domain, self.geocode_path) def geocode( self, diff --git a/src/open_inwoner/utils/logentry.py b/src/open_inwoner/utils/logentry.py index 5de1f85f5e..2c8a2c42a3 100644 --- a/src/open_inwoner/utils/logentry.py +++ b/src/open_inwoner/utils/logentry.py @@ -67,7 +67,11 @@ def addition(request, object, message=""): """ Log that an object has been successfully added. """ - logger.info(f"Added: {object}, {message}. \n{request}") + logger.info( + ("Added: {object}, {message}. \n{request}").format( + object=object, message=message, request=request + ) + ) TimelineLog.log_from_request( request=request, content_object=object, @@ -82,7 +86,11 @@ def change(request, object, message): """ Log that an object has been successfully changed. """ - logger.info(f"Changed: {object}, {message}. \n{request}") + logger.info( + ("Changed: {object}, {message}. \n{request}").format( + object=object, message=message, request=request + ) + ) TimelineLog.log_from_request( request=request, content_object=object, @@ -97,7 +105,11 @@ def deletion(request, object, message=""): """ Log that an object was deleted. """ - logger.info(f"Deleted: {object}, {message}. \n{request}") + logger.info( + ("Deleted: {object}, {message}. \n{request}").format( + object=object, message=message, request=request + ) + ) TimelineLog.log_from_request( request=request, content_object=object, @@ -113,7 +125,11 @@ def user_action(request, object, message): Log a generic action done by a user, useful for when add/change/delete aren't appropriate. """ - logger.info(f"User action: {object}, {message}. \n{request}") + logger.info( + ("User action: {object}, {message}. \n{request}").format( + object=object, message=message, request=request + ) + ) TimelineLog.log_from_request( request=request, content_object=object, diff --git a/src/open_inwoner/utils/mixins.py b/src/open_inwoner/utils/mixins.py index a0c8f6e1cc..cb47908a57 100644 --- a/src/open_inwoner/utils/mixins.py +++ b/src/open_inwoner/utils/mixins.py @@ -41,7 +41,11 @@ def create_throttle_key(self): :rtype string Use as key to save the last access """ - return f"throttling_{self.get_throttle_identifier()}_{self.throttle_name}_{self.get_throttle_window()}" + return "throttling_{id}_{throttle_name}_{window}".format( + id=self.get_throttle_identifier(), + throttle_name=self.throttle_name, + window=self.get_throttle_window(), + ) def get_throttle_window(self): """ diff --git a/src/open_inwoner/utils/schema.py b/src/open_inwoner/utils/schema.py index 15c40c23fb..9ccca0a6ff 100644 --- a/src/open_inwoner/utils/schema.py +++ b/src/open_inwoner/utils/schema.py @@ -1,10 +1,12 @@ +from typing import Type + from drf_spectacular.plumbing import force_instance from drf_spectacular.utils import OpenApiParameter from rest_framework import serializers def input_serializer_to_parameters( - serializer_class: type[serializers.Serializer], + serializer_class: Type[serializers.Serializer], ) -> list[OpenApiParameter]: serializer = force_instance(serializer_class) parameters = [] diff --git a/src/open_inwoner/utils/templatetags/utils.py b/src/open_inwoner/utils/templatetags/utils.py index db448d047b..83a82696a5 100644 --- a/src/open_inwoner/utils/templatetags/utils.py +++ b/src/open_inwoner/utils/templatetags/utils.py @@ -58,7 +58,7 @@ def placekitten(width=800, height=600): {%placekitten %} {%placekitten 200 200 %} """ - return format_html(f'') + return format_html(''.format(placekitten_src(width, height))) @register.simple_tag @@ -71,7 +71,7 @@ def placekitten_src(width=800, height=600): {% placekitten_src 200 200 as mobile_src %} {% include 'components/image/image.html' with mobile_src=mobile_src src=src alt='placekitten' only %} """ - return f"//placekitten.com/{width}/{height}" + return "//placekitten.com/{}/{}".format(width, height) @register.simple_tag diff --git a/src/open_inwoner/utils/tests/test_glom.py b/src/open_inwoner/utils/tests/test_glom.py index b497588d22..013b43f439 100644 --- a/src/open_inwoner/utils/tests/test_glom.py +++ b/src/open_inwoner/utils/tests/test_glom.py @@ -9,6 +9,6 @@ def test_glom_multiple(self): "aa": {"bb": 1}, "cc": {"dd": 2}, } - self.assertEqual(glom_multiple(obj, ("aa.bb", "cc.dd")), 1) - self.assertEqual(glom_multiple(obj, ("aa.xyz", "cc.dd")), 2) - self.assertEqual(glom_multiple(obj, ("aa.xyz", "cc.xyz"), default=999), 999) + self.assertEquals(glom_multiple(obj, ("aa.bb", "cc.dd")), 1) + self.assertEquals(glom_multiple(obj, ("aa.xyz", "cc.dd")), 2) + self.assertEquals(glom_multiple(obj, ("aa.xyz", "cc.xyz"), default=999), 999) diff --git a/src/open_inwoner/utils/text.py b/src/open_inwoner/utils/text.py index 021df0e26c..046a56394c 100644 --- a/src/open_inwoner/utils/text.py +++ b/src/open_inwoner/utils/text.py @@ -11,7 +11,7 @@ def middle_truncate(value: str, length: int, dots="...") -> str: def html_tag_wrap_format(format_str: str, tag: str, **kwargs) -> str: assert kwargs, "expected replacment kwargs" - html_tag = f"<{tag}>{{}}" + html_tag = "<{}>{{}}".format(tag, tag) replace = { name: format_html(html_tag, force_str(value)) for name, value in kwargs.items() } diff --git a/src/open_inwoner/utils/validators.py b/src/open_inwoner/utils/validators.py index 69f32bb724..c7a0aa739b 100644 --- a/src/open_inwoner/utils/validators.py +++ b/src/open_inwoner/utils/validators.py @@ -128,7 +128,7 @@ def __call__(self, value): Validates that the input matches the regular expression. """ if not self.regex.search(force_str(value)): - message = f"{self.message}: {force_str(value)}" + message = "{}: {}".format(self.message, force_str(value)) raise ValidationError(message, code=self.code) diff --git a/src/openklant2/_resources/base.py b/src/openklant2/_resources/base.py index 8a1da7bcb9..c4fb99dce9 100644 --- a/src/openklant2/_resources/base.py +++ b/src/openklant2/_resources/base.py @@ -1,8 +1,14 @@ import json import logging -from collections.abc import Callable, Generator, Mapping, MutableMapping from typing import ( Any, + Callable, + Dict, + Generator, + List, + Mapping, + MutableMapping, + Optional, ParamSpec, TypeGuard, TypeVar, @@ -36,8 +42,8 @@ JSONPrimitive = Union[str, int, None, float] -JSONValue = Union[JSONPrimitive, "JSONObject", list["JSONValue"]] -JSONObject = dict[str, JSONValue] +JSONValue = Union[JSONPrimitive, "JSONObject", List["JSONValue"]] +JSONObject = Dict[str, JSONValue] P = ParamSpec("P") T = TypeVar("T") @@ -113,7 +119,7 @@ def _process_params(params: Mapping | None) -> None | Mapping: def _paginator( self, paginated_data: PaginatedResponseBody[T], - max_requests: int | None = None, + max_requests: Optional[int] = None, ) -> Generator[T, Any, None]: def row_iterator( _data: PaginatedResponseBody[T], num_requests=0 diff --git a/src/openklant2/_resources/partij.py b/src/openklant2/_resources/partij.py index 776c9ca9e8..4016635211 100644 --- a/src/openklant2/_resources/partij.py +++ b/src/openklant2/_resources/partij.py @@ -1,5 +1,5 @@ import uuid -from typing import cast +from typing import Optional, cast from ape_pie import APIClient @@ -26,7 +26,7 @@ def list( return cast(PaginatedResponseBody[Partij], self.process_response(response)) def retrieve( - self, /, uuid: str | uuid.UUID, *, params: PartijRetrieveParams | None = None + self, /, uuid: str | uuid.UUID, *, params: Optional[PartijRetrieveParams] = None ) -> Partij: response = self._get(f"{self.base_path}/{str(uuid)}", params=params) return cast(Partij, self.process_response(response)) diff --git a/src/openklant2/factories/helpers.py b/src/openklant2/factories/helpers.py index 69c8cc6862..e27541d505 100644 --- a/src/openklant2/factories/helpers.py +++ b/src/openklant2/factories/helpers.py @@ -11,7 +11,7 @@ def decorator(cls: type[factory.Factory]): def validate(obj, *args, **kwargs): validator.validate_python(obj) - cls.post_generation_validator = validate + setattr(cls, "post_generation_validator", validate) return cls diff --git a/src/openklant2/tests/test_partij.py b/src/openklant2/tests/test_partij.py index 7dadaf1e80..11f1b006dd 100644 --- a/src/openklant2/tests/test_partij.py +++ b/src/openklant2/tests/test_partij.py @@ -93,6 +93,7 @@ def test_create_persoon(client) -> None: "digitaleAdressen": None, "rekeningnummers": None, "voorkeursRekeningnummer": None, + "soortPartij": "persoon", "voorkeurstaal": "nld", "indicatieActief": True, "indicatieGeheimhouding": False, diff --git a/src/openklant2/types/resources/klant_contact.py b/src/openklant2/types/resources/klant_contact.py index 09fb8fe410..98e10435ad 100644 --- a/src/openklant2/types/resources/klant_contact.py +++ b/src/openklant2/types/resources/klant_contact.py @@ -1,4 +1,4 @@ -from typing import Literal, NotRequired, Required +from typing import Literal, NotRequired, Optional, Required from pydantic import TypeAdapter from typing_extensions import TypedDict @@ -79,7 +79,7 @@ class KlantContact(TypedDict): nummer: str kanaal: str onderwerp: str - inhoud: str | None + inhoud: Optional[str] indicatieContactGelukt: Required[bool | None] taal: LanguageCode