From e6901819890aa3c89beed4415c71b9472ea0ab51 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll <82368148+Tmpecho@users.noreply.github.com> Date: Mon, 28 Oct 2024 20:08:00 +0100 Subject: [PATCH] Refactor/minor code cleanup (#884) * Prefix unused variable names with underscore, remove redundant parenthesis, split long lines into several, rename functions to snake_case, Signed-off-by: Tmpecho * Update CHANGELOG.md Signed-off-by: Tmpecho * Make constant uppercase Signed-off-by: Tmpecho * Empty-Commit --------- Signed-off-by: Tmpecho Co-authored-by: Mads Nylund <73914541+MadsNyl@users.noreply.github.com> --- CHANGELOG.md | 1 + .../serializers/change_password.py | 1 + .../serializers/reset_password.py | 5 ++++ app/badge/filters/badge.py | 10 +++---- app/career/filters/job_post.py | 4 +-- app/career/views/weekly_business.py | 2 +- app/common/azure_file_handler.py | 22 +++++++------- app/common/enums.py | 4 +-- app/common/file_handler.py | 10 +++---- app/common/tasks.py | 2 +- app/common/tests/test_azure_filehandler.py | 2 +- app/communication/factories/mail_factory.py | 2 +- app/communication/models/banner.py | 2 +- app/communication/models/mail.py | 5 ++-- app/communication/tasks.py | 2 +- app/communication/tests/test_banner_model.py | 6 ++-- app/communication/views/banner.py | 4 +-- app/communication/views/notification.py | 2 +- .../views/user_notification_setting.py | 2 +- app/content/admin/admin.py | 2 +- .../factories/priority_pool_factory.py | 2 +- app/content/filters/event.py | 4 +-- app/content/filters/strike.py | 4 +-- app/content/filters/user.py | 12 ++++---- app/content/models/registration.py | 3 +- app/content/models/short_link.py | 2 +- app/content/models/strike.py | 8 ++--- app/content/models/user.py | 5 ++-- app/content/serializers/event.py | 4 +-- app/content/tasks/event.py | 12 ++++---- app/content/tests/test_strike_model.py | 14 ++++----- app/content/util/event_utils.py | 21 ++----------- app/content/util/feide_utils.py | 4 +-- app/content/views/accept_form.py | 4 ++- app/content/views/event.py | 14 ++++----- app/content/views/page.py | 2 +- app/content/views/registration.py | 2 +- app/content/views/upload.py | 6 ++-- app/content/views/user.py | 30 +++++++++---------- app/content/views/user_bio.py | 2 +- app/content/views/user_calendar_events.py | 3 +- app/emoji/views/reaction.py | 2 +- app/forms/models/forms.py | 2 +- app/forms/views/form.py | 2 +- app/forms/views/submission.py | 2 +- app/gallery/views/picture.py | 2 +- app/group/filters/membership.py | 2 +- app/group/serializers/group.py | 4 +-- app/group/views/fine.py | 13 ++++---- app/group/views/group.py | 2 +- app/group/views/law.py | 2 +- app/group/views/membership.py | 13 ++++++-- app/payment/models/order.py | 4 +-- app/payment/tasks.py | 2 +- app/payment/util/payment_utils.py | 2 +- app/payment/views/vipps_callback.py | 2 +- app/util/export_user_data.py | 2 -- app/util/migrations.py | 2 +- app/util/utils.py | 4 +-- 59 files changed, 158 insertions(+), 154 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4c74f5f2..4263f47a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ --- ## Neste versjon +- 🎨**Overordnet**. Endret variabel og funksjonsnavn til å følge konvensjoner og andre små endringer. - ✨ **Filtrering**. Admin kan nå filtere deltakere av et arrangement på studie, studieår, om deltakere har allergier, (om deltakere godtar å bli tatt bilde av, om deltakere har ankommet), i tillegg til søk på fornavn og etternavn. ## Versjon 2024.10.11 diff --git a/app/authentication/serializers/change_password.py b/app/authentication/serializers/change_password.py index bc1dc685c..5d214bdce 100644 --- a/app/authentication/serializers/change_password.py +++ b/app/authentication/serializers/change_password.py @@ -11,6 +11,7 @@ class ChangePasswordSerializer(serializers.Serializer): set_password_form_class = SetPasswordForm def __init__(self, *args, **kwargs): + self.set_password_form = None self.old_password_field_enabled = getattr( settings, "OLD_PASSWORD_FIELD_ENABLED", True ) diff --git a/app/authentication/serializers/reset_password.py b/app/authentication/serializers/reset_password.py index 73baeb6ff..67d612d2d 100644 --- a/app/authentication/serializers/reset_password.py +++ b/app/authentication/serializers/reset_password.py @@ -2,6 +2,7 @@ from django.contrib.auth.forms import PasswordResetForm from rest_framework import serializers +from rest_framework.fields import empty from sentry_sdk import capture_exception @@ -16,6 +17,10 @@ class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm + def __init__(self, instance=None, data=empty, **kwargs): + super().__init__(instance, data, kwargs) + self.reset_form = None + def validate_email(self, value): # Create PasswordResetForm with the serializer try: diff --git a/app/badge/filters/badge.py b/app/badge/filters/badge.py index 91e91a038..a7c887de1 100644 --- a/app/badge/filters/badge.py +++ b/app/badge/filters/badge.py @@ -23,15 +23,15 @@ class UserWithBadgesFilter(FilterSet): queryset=BadgeCategory.objects.all(), ) - def filter_category(self, queryset, name, value): + def filter_category(self, queryset, _name, value): return queryset.filter(user_badges__badge__badge_category=value) - def filter_is_in_study(self, queryset, name, value): + def filter_is_in_study(self, queryset, _name, value): return queryset.filter( memberships__group__slug=value, memberships__group__type=GroupType.STUDY ) - def filter_is_in_studyyear(self, queryset, name, value): + def filter_is_in_studyyear(self, queryset, _name, value): return queryset.filter( memberships__group__slug=value, memberships__group__type=GroupType.STUDYYEAR ) @@ -49,7 +49,7 @@ class UserWithSpecificBadgeFilter(FilterSet): study = filters.NumberFilter(method="filter_study") studyyear = filters.NumberFilter(method="filter_studyyear") - def filter_study(self, queryset, name, value): + def filter_study(self, queryset, _name, value): return queryset.filter( Exists( Membership.objects.filter( @@ -60,7 +60,7 @@ def filter_study(self, queryset, name, value): ) ) - def filter_studyyear(self, queryset, name, value): + def filter_studyyear(self, queryset, _name, value): return queryset.filter( Exists( Membership.objects.filter( diff --git a/app/career/filters/job_post.py b/app/career/filters/job_post.py index 179b26bfc..bcafc9d76 100644 --- a/app/career/filters/job_post.py +++ b/app/career/filters/job_post.py @@ -20,12 +20,12 @@ class Meta: model: JobPost fields = ["expired", "job_type"] - def filter_expired(self, queryset, name, value): + def filter_expired(self, queryset, _name, value): if value: return queryset.filter(deadline__lt=yesterday()).order_by("-deadline") return queryset.filter(deadline__gte=yesterday()).order_by("deadline") - def filter_classes(self, queryset, name, value): + def filter_classes(self, queryset, _name, value): query = Q() for year in value: query |= Q(class_start__lte=year, class_end__gte=year) diff --git a/app/career/views/weekly_business.py b/app/career/views/weekly_business.py index d19bf38f9..657c3af04 100644 --- a/app/career/views/weekly_business.py +++ b/app/career/views/weekly_business.py @@ -29,7 +29,7 @@ def get_queryset(self): in_future_this_year_filter = Q(year=now().year) & Q(week__gte=week_nr(now())) next_year_filter = Q(year__gt=now().year) return WeeklyBusiness.objects.filter( - (in_future_this_year_filter) | next_year_filter + in_future_this_year_filter | next_year_filter ).order_by("year", "week") def list(self, request, *args, **kwargs): diff --git a/app/common/azure_file_handler.py b/app/common/azure_file_handler.py index 3476f422e..b963ba4b0 100644 --- a/app/common/azure_file_handler.py +++ b/app/common/azure_file_handler.py @@ -13,7 +13,7 @@ def __init__(self, blob=None, url=None): self.blob = blob self.url = url if url: - data = self.getContainerAndNameFromUrl() + data = self.get_container_and_name_from_url() self.containerName = data[0] self.blobName = data[1] @@ -29,24 +29,24 @@ def get_or_create_container(self, name="default"): container = blob_service_client.create_container(name, public_access="blob") return container - def getContainerAndNameFromUrl(self): + def get_container_and_name_from_url(self): import urllib.parse url = urllib.parse.unquote(self.url) # fmt: off - return re.sub("\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*/", "", url).split("/") # noqa: W605 + return re.sub("\w+:/{2}[\d\w-]+(\.[\d\w-]+)*/", "", url).split("/") # noqa: W605 # fmt: on - def uploadBlob(self): - "Uploads the given blob to Azure and returns a url to the blob" + def upload_blob(self): + """Uploads the given blob to Azure and returns a url to the blob""" if not self.blob: raise ValueError("Du må sende med en blob for som skal lastes opp") - self.checkBlobSize() - containerName = self.getContainerNameFromBlob() - container = self.get_or_create_container(containerName) + self.check_blob_size() + container_name = self.get_container_name_from_blob() + container = self.get_or_create_container(container_name) - blob_name = f"{uuid.uuid4()}{self.getBlobName()}" + blob_name = f"{uuid.uuid4()}{self.get_blob_name()}" content_settings = ContentSettings( content_type=self.blob.content_type if self.blob.content_type else None, @@ -62,8 +62,8 @@ def uploadBlob(self): return blob_client.url raise ValueError("Noe gikk galt under filopplastningen") - def deleteBlob(self): - "Delete a blob by it's url" + def delete_blob(self): + """Delete a blob by it's url""" if not self.blobName and not self.containerName: raise ValueError("Du kan ikke slette en blob uten en url") diff --git a/app/common/enums.py b/app/common/enums.py index 68afaa78e..20d1f7b31 100644 --- a/app/common/enums.py +++ b/app/common/enums.py @@ -75,11 +75,11 @@ class AdminGroup(models.TextChoices): @classmethod def all(cls): - return (cls.HS, cls.INDEX, cls.NOK, cls.PROMO, cls.SOSIALEN, cls.KOK) + return cls.HS, cls.INDEX, cls.NOK, cls.PROMO, cls.SOSIALEN, cls.KOK @classmethod def admin(cls): - return (cls.HS, cls.INDEX) + return cls.HS, cls.INDEX class Groups(models.TextChoices): diff --git a/app/common/file_handler.py b/app/common/file_handler.py index 3b7450753..68a566ede 100644 --- a/app/common/file_handler.py +++ b/app/common/file_handler.py @@ -14,22 +14,22 @@ def __init__(self, blob=None): def get_or_create_container(self, name="default"): pass - def getBlobName(self): + def get_blob_name(self): return self.blob.name if self.blob.name else "" - def getContainerNameFromBlob(self): + def get_container_name_from_blob(self): return ( "".join(e for e in self.blob.content_type if e.isalnum()) if self.blob.content_type else "default" ) - def checkBlobSize(self): + def check_blob_size(self): if self.blob.size > self.SIZE_50_MB: raise ValueError("Filen kan ikke være større enn 50 MB") @abstractmethod - def uploadBlob(self): + def upload_blob(self): pass @@ -43,6 +43,6 @@ def replace_file(instance_image, validated_data_image): if instance_image and instance_image != validated_data_image: if settings.AZURE_BLOB_STORAGE_NAME in instance_image: try: - AzureFileHandler(url=instance_image).deleteBlob() + AzureFileHandler(url=instance_image).delete_blob() except Exception as e: capture_exception(e) diff --git a/app/common/tasks.py b/app/common/tasks.py index a2fe0cc0d..97b4a2b41 100644 --- a/app/common/tasks.py +++ b/app/common/tasks.py @@ -3,7 +3,7 @@ @app.task(bind=True, base=BaseTask) -def delete_old_log_entries(self, *args, **kwargs): +def delete_old_log_entries(self, *_args, **_kwargs): from datetime import timedelta from django.contrib.admin.models import LogEntry diff --git a/app/common/tests/test_azure_filehandler.py b/app/common/tests/test_azure_filehandler.py index 5b9fcf6cb..b8a649eee 100644 --- a/app/common/tests/test_azure_filehandler.py +++ b/app/common/tests/test_azure_filehandler.py @@ -9,6 +9,6 @@ def test_get_getContainerAndNameFromUrl(): handler = AzureFileHandler( url=f"https://{settings.AZURE_BLOB_STORAGE_NAME}/{container_name}/{file_name}" ) - data = handler.getContainerAndNameFromUrl() + data = handler.get_container_and_name_from_url() assert data[0] == container_name assert data[1] == file_name diff --git a/app/communication/factories/mail_factory.py b/app/communication/factories/mail_factory.py index 67da2a509..271ee0b8b 100644 --- a/app/communication/factories/mail_factory.py +++ b/app/communication/factories/mail_factory.py @@ -12,7 +12,7 @@ class Meta: body = factory.Faker("paragraph", nb_sentences=10) @factory.post_generation - def users(self, create, extracted, **kwargs): + def users(self, create, extracted, **_kwargs): """Add users to the mail: `MailFactory.create(users=(user1, user2, user3))`""" if not create or not extracted: # Simple build, or nothing to add, do nothing. diff --git a/app/communication/models/banner.py b/app/communication/models/banner.py index f40fb1dde..61f7cfe21 100644 --- a/app/communication/models/banner.py +++ b/app/communication/models/banner.py @@ -66,5 +66,5 @@ def is_visible(self): return self.visible_from <= now() <= self.visible_until @classmethod - def has_visible_permission(cls, request): + def has_visible_permission(cls, _request): return True diff --git a/app/communication/models/mail.py b/app/communication/models/mail.py index e4ba7ec26..692fdd004 100644 --- a/app/communication/models/mail.py +++ b/app/communication/models/mail.py @@ -27,7 +27,7 @@ class Meta: def send(self, connection): from app.communication.notifier import send_html_email - emails = (user.email for user in self.users.all()) + emails = [user.email for user in self.users.all()] is_success = send_html_email( to_mails=emails, html=self.body, @@ -40,4 +40,5 @@ def send(self, connection): return is_success def __str__(self): - return f"\"{self.subject}\", to {self.users.all()[0] if self.users.count() == 1 else f'{self.users.count()} users'}, {'sent' if self.sent else 'eta'} {self.eta}" + return (f"\"{self.subject}\", to {self.users.all()[0] if self.users.count() == 1 else f'{self.users.count()} users'}, " + f"{'sent' if self.sent else 'eta'} {self.eta}") diff --git a/app/communication/tasks.py b/app/communication/tasks.py index fd49f1d40..f28678750 100644 --- a/app/communication/tasks.py +++ b/app/communication/tasks.py @@ -5,7 +5,7 @@ @app.task(bind=True, base=BaseTask) -def send_due_mails(self, *args, **kwargs): +def send_due_mails(self, *_args, **_kwargs): from django.core.mail import get_connection from app.communication.models.mail import Mail diff --git a/app/communication/tests/test_banner_model.py b/app/communication/tests/test_banner_model.py index e46051d0a..cbb2936f6 100644 --- a/app/communication/tests/test_banner_model.py +++ b/app/communication/tests/test_banner_model.py @@ -7,7 +7,7 @@ DatesMixedError, ) from app.communication.factories.banner_factory import BannerFactory -from app.util.utils import getTimezone, now +from app.util.utils import get_timezone, now @pytest.mark.parametrize( @@ -27,8 +27,8 @@ def test_two_banners_can_not_be_visible_simultaneously_in_any_period( This test uses timedelta and parameterize to switch visible_from and visible_until between 5 days earlier or later.""" existing_banner = BannerFactory( - visible_from=datetime(2020, 1, 1, tzinfo=getTimezone()), - visible_until=datetime(2021, 1, 1, tzinfo=getTimezone()), + visible_from=datetime(2020, 1, 1, tzinfo=get_timezone()), + visible_until=datetime(2021, 1, 1, tzinfo=get_timezone()), ) with pytest.raises(AnotherVisibleBannerError): diff --git a/app/communication/views/banner.py b/app/communication/views/banner.py index 4dd0ddd3c..888f83195 100644 --- a/app/communication/views/banner.py +++ b/app/communication/views/banner.py @@ -21,12 +21,12 @@ class Meta: model = Banner fields = ["is_visible", "is_expired"] - def filter_is_visible(self, queryset, name, value): + def filter_is_visible(self, queryset, _name, value): if value: return queryset.filter(visible_from__lte=now(), visible_until__gte=now()) return queryset - def filter_is_expired(self, queryset, name, value): + def filter_is_expired(self, queryset, _name, value): if value: return queryset.filter(visible_until__lt=now()) return queryset diff --git a/app/communication/views/notification.py b/app/communication/views/notification.py index 40c614ee3..1b96fa26e 100644 --- a/app/communication/views/notification.py +++ b/app/communication/views/notification.py @@ -36,6 +36,6 @@ def update(self, request, pk): status=status.HTTP_200_OK, ) return Response( - {"detail": ("Kunne ikke oppdatere varslet")}, + {"detail": "Kunne ikke oppdatere varslet"}, status=status.HTTP_403_FORBIDDEN, ) diff --git a/app/communication/views/user_notification_setting.py b/app/communication/views/user_notification_setting.py index e24360c96..0786ac997 100644 --- a/app/communication/views/user_notification_setting.py +++ b/app/communication/views/user_notification_setting.py @@ -50,7 +50,7 @@ def create(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"], url_path="choices") - def choices(self, request, *args, **kwargs): + def choices(self, _request, *_args, **_kwargs): return Response( list( map( diff --git a/app/content/admin/admin.py b/app/content/admin/admin.py index 1a219f7e3..16191c23d 100644 --- a/app/content/admin/admin.py +++ b/app/content/admin/admin.py @@ -40,7 +40,7 @@ class StrikeAdmin(admin.ModelAdmin): ) -def admin_delete_registration(modeladmin, request, queryset): +def admin_delete_registration(_modeladmin, _request, queryset): for registration in queryset: registration.admin_unregister() diff --git a/app/content/factories/priority_pool_factory.py b/app/content/factories/priority_pool_factory.py index ec2af803e..3e783d85a 100644 --- a/app/content/factories/priority_pool_factory.py +++ b/app/content/factories/priority_pool_factory.py @@ -12,7 +12,7 @@ class Meta: event = factory.SubFactory(EventFactory) @factory.post_generation - def groups(self, create, extracted, **kwargs): + def groups(self, create, extracted, **_kwargs): if not create or not extracted: # Simple build, do nothing. return diff --git a/app/content/filters/event.py b/app/content/filters/event.py index 48ad63d35..abf189871 100644 --- a/app/content/filters/event.py +++ b/app/content/filters/event.py @@ -26,7 +26,7 @@ class Meta: model = Event fields = ["category", "organizer", "end_range", "start_range"] - def filter_open_for_sign_up(self, queryset, name, value): + def filter_open_for_sign_up(self, queryset, _name, value): if value: return queryset.filter( sign_up=True, @@ -35,7 +35,7 @@ def filter_open_for_sign_up(self, queryset, name, value): ) return queryset - def filter_user_favorites(self, queryset, name, value): + def filter_user_favorites(self, queryset, _name, value): if value and self.request.user: return queryset.filter(favorite_users__user_id=self.request.user.user_id) return queryset diff --git a/app/content/filters/strike.py b/app/content/filters/strike.py index f8b820003..75750908d 100644 --- a/app/content/filters/strike.py +++ b/app/content/filters/strike.py @@ -11,7 +11,7 @@ class StrikeFilter(FilterSet): study = filters.NumberFilter(method="filter_study") studyyear = filters.NumberFilter(method="filter_studyyear") - def filter_study(self, queryset, name, value): + def filter_study(self, queryset, _name, value): return queryset.filter( Exists( Membership.objects.filter( @@ -22,7 +22,7 @@ def filter_study(self, queryset, name, value): ) ) - def filter_studyyear(self, queryset, name, value): + def filter_studyyear(self, queryset, _name, value): return queryset.filter( Exists( Membership.objects.filter( diff --git a/app/content/filters/user.py b/app/content/filters/user.py index a189f2390..9b83b1ffa 100644 --- a/app/content/filters/user.py +++ b/app/content/filters/user.py @@ -35,28 +35,28 @@ class Meta: "in_group", ] - def filter_is_in_study(self, queryset, name, value): + def filter_is_in_study(self, queryset, _name, value): return queryset.filter( memberships__group__slug=value, memberships__group__type=GroupType.STUDY ) - def filter_is_in_studyyear(self, queryset, name, value): + def filter_is_in_studyyear(self, queryset, _name, value): return queryset.filter( memberships__group__slug=value, memberships__group__type=GroupType.STUDYYEAR ) - def filter_is_in_group(self, queryset, name, value): + def filter_is_in_group(self, queryset, _name, value): return queryset.filter(memberships__group__slug=value) - def filter_is_TIHLDE_member(self, queryset, name, value): + def filter_is_TIHLDE_member(self, queryset, _name, value): if value is False: return queryset.exclude(memberships__group__slug=Groups.TIHLDE) return queryset.filter(memberships__group__slug=Groups.TIHLDE) - def filter_has_active_strikes(self, queryset, name, value): + def filter_has_active_strikes(self, queryset, _name, value): if value is False: return queryset.exclude(strikes__in=Strike.objects.active()).distinct() return queryset.filter(strikes__in=Strike.objects.active()).distinct() - def filter_has_allowed_photo(self, queryset, name, value): + def filter_has_allowed_photo(self, queryset, _name, value): return queryset.filter(allows_photo_by_default=value) diff --git a/app/content/models/registration.py b/app/content/models/registration.py index 19c6c3790..220066371 100644 --- a/app/content/models/registration.py +++ b/app/content/models/registration.py @@ -50,7 +50,7 @@ class Meta: verbose_name_plural = "Registrations" @classmethod - def has_retrieve_permission(cls, request): + def has_retrieve_permission(cls, _request): return True @classmethod @@ -415,6 +415,7 @@ def check_registration_has_ended(self): if self.event.end_registration_at < now(): raise ValidationError("Påmeldingsfristen har passert") + # noinspection PyShadowingBuiltins def get_submissions(self, type=None): from app.forms.models import EventForm, Submission diff --git a/app/content/models/short_link.py b/app/content/models/short_link.py index 22bc61a55..9cadea0d0 100644 --- a/app/content/models/short_link.py +++ b/app/content/models/short_link.py @@ -29,7 +29,7 @@ def has_create_permission(cls, request): return super().has_write_permission(request) @classmethod - def has_destroy_permission(cls, request): + def has_destroy_permission(cls, _request): return True def has_object_write_permission(self, request): diff --git a/app/content/models/strike.py b/app/content/models/strike.py index 696dc4463..872c1651e 100644 --- a/app/content/models/strike.py +++ b/app/content/models/strike.py @@ -10,7 +10,7 @@ from app.communication.enums import UserNotificationSettingType from app.content.models import Event from app.util.models import BaseModel -from app.util.utils import getTimezone, now +from app.util.utils import get_timezone, now class Holiday: @@ -117,10 +117,10 @@ def expires_at(self): end = holiday.end start_date = datetime( - self.created_at.year, start[0], start[1], tzinfo=getTimezone() + self.created_at.year, start[0], start[1], tzinfo=get_timezone() ) end_date = datetime( - self.created_at.year, end[0], end[1], tzinfo=getTimezone() + self.created_at.year, end[0], end[1], tzinfo=get_timezone() ) if end_date < start_date: @@ -133,7 +133,7 @@ def expires_at(self): expired_date += smallest_difference + timedelta(days=1) break - return expired_date.astimezone(getTimezone()) + return expired_date.astimezone(get_timezone()) @classmethod def has_destroy_permission(cls, request): diff --git a/app/content/models/user.py b/app/content/models/user.py index 1c4ce58b7..1230fb7a6 100644 --- a/app/content/models/user.py +++ b/app/content/models/user.py @@ -209,7 +209,7 @@ def has_write_permission(cls, request): ) @classmethod - def has_create_permission(cls, request): + def has_create_permission(cls, _request): return True def has_object_write_permission(self, request): @@ -234,9 +234,10 @@ def has_object_get_user_detail_strikes_permission(self, request): ) +# noinspection PyUnusedLocal @receiver(post_save, sender=settings.AUTH_USER_MODEL) @disable_for_loaddata -def create_auth_token(sender, instance=None, created=False, **kwargs): +def create_auth_token(sender, instance=None, created=False, **_kwargs): """Generate token at creation of user""" if created: Token.objects.create(user=instance) diff --git a/app/content/serializers/event.py b/app/content/serializers/event.py index 0a731a4cb..c97704df0 100644 --- a/app/content/serializers/event.py +++ b/app/content/serializers/event.py @@ -282,7 +282,7 @@ class Meta: "allow_photo_count", ) - def get_has_attended_count(self, obj, *args, **kwargs): + def get_has_attended_count(self, obj, *_args, **_kwargs): return obj.registrations.filter(is_on_wait=False, has_attended=True).count() def get_has_allergy_count(self, obj, *args, **kwargs): @@ -307,7 +307,7 @@ def get_studyyears(self, obj, *args, **kwargs): ), ) - def get_studies(self, obj, *args, **kwargs): + def get_studies(self, obj, *_args, **_kwargs): return filter( lambda study: study["amount"] > 0, map( diff --git a/app/content/tasks/event.py b/app/content/tasks/event.py index 12da3245c..ac2e6c8a1 100644 --- a/app/content/tasks/event.py +++ b/app/content/tasks/event.py @@ -19,7 +19,7 @@ @app.task(bind=True, base=BaseTask) -def run_sign_off_deadline_reminder(self, *args, **kwargs): +def run_sign_off_deadline_reminder(self, *_args, **_kwargs): from app.content.models.event import Event try: @@ -41,7 +41,7 @@ def run_sign_off_deadline_reminder(self, *args, **kwargs): @app.task(bind=True, base=BaseTask) -def run_post_event_actions(self, *args, **kwargs): +def run_post_event_actions(self, *_args, **_kwargs): from app.content.models.event import Event try: @@ -61,7 +61,7 @@ def run_post_event_actions(self, *args, **kwargs): @app.task(bind=True, base=BaseTask) -def run_sign_up_start_notifier(self, *args, **kwargs): +def run_sign_up_start_notifier(self, *_args, **_kwargs): from app.content.models.event import Event try: @@ -82,7 +82,7 @@ def run_sign_up_start_notifier(self, *args, **kwargs): capture_exception(e) -def __sign_off_deadline_reminder(event, *args, **kwargs): +def __sign_off_deadline_reminder(event, *_args, **_kwargs): from app.content.models import User users_not_on_wait = User.objects.filter( @@ -117,7 +117,7 @@ def __sign_off_deadline_reminder(event, *args, **kwargs): event.save(update_fields=["runned_sign_off_deadline_reminder"]) -def __post_event_actions(event, *args, **kwargs): +def __post_event_actions(event, *_args, **_kwargs): from app.content.models import User if event.can_cause_strikes: @@ -149,7 +149,7 @@ def __post_event_actions(event, *args, **kwargs): event.save(update_fields=["runned_post_event_actions"]) -def __sign_up_start_notifier(event, *args, **kwargs): +def __sign_up_start_notifier(event, *_args, **_kwargs): description = f'Påmelding til "{event.title}" har nå åpnet! 🏃 Arrangementet starter {datetime_format(event.start_date)} og har {event.limit} plasser. Påmeldingen er åpen frem til {datetime_format(event.end_registration_at)}, men husk at det kan bli fullt før det. ⏲️' CHANNEL_ID = ( diff --git a/app/content/tests/test_strike_model.py b/app/content/tests/test_strike_model.py index de90371c4..64afee292 100644 --- a/app/content/tests/test_strike_model.py +++ b/app/content/tests/test_strike_model.py @@ -5,7 +5,7 @@ from app.content.factories import StrikeFactory from app.content.models.strike import STRIKE_DURATION_IN_DAYS -from app.util.utils import getTimezone +from app.util.utils import get_timezone @pytest.mark.django_db @@ -30,8 +30,8 @@ def test_strike_is_active_or_not_with_freeze_through_winter_holiday( mock_now, today, created_at, expected_result ): """Strikes are frozen in winter from the 29th of November to the 1st of January.""" - today = today.replace(tzinfo=getTimezone()) - created_at = created_at.replace(tzinfo=getTimezone()) + today = today.replace(tzinfo=get_timezone()) + created_at = created_at.replace(tzinfo=get_timezone()) mock_now.return_value = today strike = StrikeFactory.build(created_at=created_at) @@ -63,8 +63,8 @@ def test_strike_is_active_or_not_with_freeze_through_summer_holiday( mock_now, today, created_at, expected_result ): """Strikes are frozen in summer from the 10th of May to 15th of August.""" - today = today.replace(tzinfo=getTimezone()) - created_at = created_at.replace(tzinfo=getTimezone()) + today = today.replace(tzinfo=get_timezone()) + created_at = created_at.replace(tzinfo=get_timezone()) mock_now.return_value = today strike = StrikeFactory.build(created_at=created_at) @@ -89,7 +89,7 @@ def test_strike_is_active_or_not_with_freeze_through_summer_holiday( ) def test_active_days_of_a_strike_with_freeze_through_holidays(created_at, days_active): """Days active is the amount of days a strike is active which is at least 20 days""" - created_at = created_at.replace(tzinfo=getTimezone()) + created_at = created_at.replace(tzinfo=get_timezone()) strike = StrikeFactory.build(created_at=created_at) @@ -117,7 +117,7 @@ def test_year_of_expire_date_different_than_created_year_with_freeze_through_win ): """A strike should have a different year of expired date if created less 20 days before the winter holiday""" - created_at = created_at.replace(tzinfo=getTimezone()) + created_at = created_at.replace(tzinfo=get_timezone()) strike = StrikeFactory.build(created_at=created_at) diff --git a/app/content/util/event_utils.py b/app/content/util/event_utils.py index d63431908..e611adc96 100644 --- a/app/content/util/event_utils.py +++ b/app/content/util/event_utils.py @@ -1,14 +1,11 @@ -import os -from datetime import datetime - from sentry_sdk import capture_exception from app.content.exceptions import RefundFailedError from app.payment.tasks import check_if_has_paid from app.payment.util.payment_utils import ( - get_new_access_token, initiate_payment, refund_payment, + check_access_token ) @@ -45,13 +42,7 @@ def create_vipps_order(order_id, event, transaction_text, fallback): Creates vipps order, and returns the url. """ - access_token = os.environ.get("PAYMENT_ACCESS_TOKEN") - expires_at = os.environ.get("PAYMENT_ACCESS_TOKEN_EXPIRES_AT") - - if not access_token or datetime.now() >= datetime.fromtimestamp(int(expires_at)): - (expires_at, access_token) = get_new_access_token() - os.environ.update({"PAYMENT_ACCESS_TOKEN": access_token}) - os.environ.update({"PAYMENT_ACCESS_TOKEN_EXPIRES_AT": str(expires_at)}) + access_token = check_access_token() event_price = int(event.paid_information.price * 100) @@ -71,13 +62,7 @@ def refund_vipps_order(order_id, event, transaction_text): Refunds vipps order. """ - access_token = os.environ.get("PAYMENT_ACCESS_TOKEN") - expires_at = os.environ.get("PAYMENT_ACCESS_TOKEN_EXPIRES_AT") - - if not access_token or datetime.now() >= datetime.fromtimestamp(int(expires_at)): - (expires_at, access_token) = get_new_access_token() - os.environ.update({"PAYMENT_ACCESS_TOKEN": access_token}) - os.environ.update({"PAYMENT_ACCESS_TOKEN_EXPIRES_AT": str(expires_at)}) + access_token = check_access_token() event_price = int(event.paid_information.price) * 100 diff --git a/app/content/util/feide_utils.py b/app/content/util/feide_utils.py index bc38cc963..bbce707c3 100644 --- a/app/content/util/feide_utils.py +++ b/app/content/util/feide_utils.py @@ -52,7 +52,7 @@ def get_feide_tokens(code: str) -> tuple[str, str]: if "access_token" not in json or "id_token" not in json: raise FeideTokenNotFoundError() - return (json["access_token"], json["id_token"]) + return json["access_token"], json["id_token"] def get_feide_user_info_from_jwt(jwt_token: str) -> tuple[str, str]: @@ -73,7 +73,7 @@ def get_feide_user_info_from_jwt(jwt_token: str) -> tuple[str, str]: if not feide_username: raise FeideUsernameNotFoundError() - return (user_info["name"], feide_username) + return user_info["name"], feide_username def get_feide_user_groups(access_token: str) -> list[str]: diff --git a/app/content/views/accept_form.py b/app/content/views/accept_form.py index 74a3bd982..44e4fe6f7 100644 --- a/app/content/views/accept_form.py +++ b/app/content/views/accept_form.py @@ -23,7 +23,9 @@ def accept_form(request): if len(types) == 1 and types[0].lower() == "annonse" else MAIL_NOK_LEADER ) - title = f"{body['info']['bedrift']} vil ha {', '.join(types[:-1])}{' og ' if len(types) > 1 else ''}{', '.join(types[-1:])}, {', '.join(times[:-1])}{' og ' if len(times) > 1 else ''}{', '.join(times[-1:])}" + title = (f"{body['info']['bedrift']} vil ha {', '.join(types[:-1])}" + f"{' og ' if len(types) > 1 else ''}{', '.join(types[-1:])}, " + f"{', '.join(times[:-1])}{' og ' if len(times) > 1 else ''}{', '.join(times[-1:])}") is_success = send_html_email( to_mails=[to_mail], diff --git a/app/content/views/event.py b/app/content/views/event.py index ecb522572..9827120cc 100644 --- a/app/content/views/event.py +++ b/app/content/views/event.py @@ -170,7 +170,7 @@ def destroy(self, request, *args, **kwargs): super().destroy(request, *args, **kwargs) return Response( - {"detail": ("Arrangementet ble slettet")}, status=status.HTTP_200_OK + {"detail": "Arrangementet ble slettet"}, status=status.HTTP_200_OK ) @action( @@ -179,7 +179,7 @@ def destroy(self, request, *args, **kwargs): url_path="favorite", permission_classes=(IsMember,), ) - def user_favorite(self, request, pk, *args, **kwargs): + def user_favorite(self, request, pk, *_args, **_kwargs): event = get_object_or_404(Event, id=pk) if request.method == "PUT": @@ -202,7 +202,7 @@ def user_favorite(self, request, pk, *args, **kwargs): methods=["get"], url_path="public_registrations", ) - def get_public_event_registrations(self, request, pk, *args, **kwargs): + def get_public_event_registrations(self, request, pk, *_args, **_kwargs): event = get_object_or_404(Event, id=pk) registrations = event.get_participants() return self.paginate_response( @@ -216,7 +216,7 @@ def get_public_event_registrations(self, request, pk, *args, **kwargs): methods=["post"], url_path="notify", ) - def notify_registered_users(self, request, *args, **kwargs): + def notify_registered_users(self, request, *_args, **_kwargs): try: title = request.data["title"] message = request.data["message"] @@ -242,7 +242,7 @@ def notify_registered_users(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"], url_path="admin") - def get_events_where_is_admin(self, request, *args, **kwargs): + def get_events_where_is_admin(self, request, *_args, **_kwargs): if not self.request.user: return Response( {"detail": "Du har ikke tilgang til å opprette/redigere arrangementer"}, @@ -271,7 +271,7 @@ def get_events_where_is_admin(self, request, *args, **kwargs): ) @action(detail=True, methods=["get"], url_path="statistics") - def statistics(self, request, *args, **kwargs): + def statistics(self, request, *_args, **_kwargs): event = self.get_object() serializer = EventStatisticsSerializer(event, context={"request": request}) return Response(serializer.data, status=status.HTTP_200_OK) @@ -285,7 +285,7 @@ def statistics(self, request, *args, **kwargs): FormParser, ), ) - def mail_gift_cards(self, request, *args, **kwargs): + def mail_gift_cards(self, request, *_args, **_kwargs): event = self.get_object() dispatcher = request.user diff --git a/app/content/views/page.py b/app/content/views/page.py index a9f02b98c..d509a53c7 100644 --- a/app/content/views/page.py +++ b/app/content/views/page.py @@ -175,7 +175,7 @@ def destroy(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"]) - def tree(self, request, *args, **kwargs): + def tree(self, _request, *_args, **_kwargs): root = Page.objects.get(parent=None) serializer = PageTreeSerializer(root) return Response(serializer.data, status=status.HTTP_200_OK) diff --git a/app/content/views/registration.py b/app/content/views/registration.py index 0aa13b3a8..4aa3bf68c 100644 --- a/app/content/views/registration.py +++ b/app/content/views/registration.py @@ -154,7 +154,7 @@ def _admin_unregister(self, registration): ) @action(detail=False, methods=["post"], url_path="add") - def add_registration(self, request, *args, **kwargs): + def add_registration(self, request, *_args, **_kwargs): """Add registration to event for admins""" if not is_admin_group_user(request): diff --git a/app/content/views/upload.py b/app/content/views/upload.py index 669c81d15..b9816e433 100644 --- a/app/content/views/upload.py +++ b/app/content/views/upload.py @@ -27,7 +27,7 @@ def upload(request): key = list(request.FILES.keys())[0] blob = request.FILES[key] - url = AzureFileHandler(blob).uploadBlob() + url = AzureFileHandler(blob).upload_blob() return Response( {"url": url}, status=status.HTTP_200_OK, @@ -41,14 +41,14 @@ def upload(request): @api_view(["DELETE"]) @permission_classes([IsMember]) -def delete(request, container_name, blob_name): +def delete(_request, container_name, blob_name): """Method for deleting files from Azure Blob Storage, only allowed for members""" try: handler = AzureFileHandler() handler.blobName = blob_name handler.containerName = container_name - handler.deleteBlob() + handler.delete_blob() return Response( {"detail": "Filen ble slettet"}, status=status.HTTP_200_OK, diff --git a/app/content/views/user.py b/app/content/views/user.py index bb3e67c42..fd9bf1ff4 100644 --- a/app/content/views/user.py +++ b/app/content/views/user.py @@ -148,7 +148,7 @@ def _get_user(self, request, pk): return get_object_or_404(User, user_id=pk) @action(detail=False, methods=["post"], url_path="me/slack") - def connect_to_slack(self, request, *args, **kwargs): + def connect_to_slack(self, request, *_args, **_kwargs): user = self.request.user self.check_object_permissions(self.request, user) @@ -171,7 +171,7 @@ def connect_to_slack(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"], url_path="me/permissions") - def get_user_permissions(self, request, *args, **kwargs): + def get_user_permissions(self, request, *_args, **_kwargs): try: serializer = UserPermissionsSerializer( request.user, context={"request": request} @@ -184,7 +184,7 @@ def get_user_permissions(self, request, *args, **kwargs): ) @action(detail=True, methods=["get"], url_path="memberships") - def get_user_memberships(self, request, pk, *args, **kwargs): + def get_user_memberships(self, request, pk, *_args, **_kwargs): user = self._get_user(request, pk) self.check_object_permissions(self.request, user) @@ -198,7 +198,7 @@ def get_user_memberships(self, request, pk, *args, **kwargs): ) @action(detail=True, methods=["get"], url_path="memberships-with-fines") - def get_user_memberships_with_fines(self, request, pk, *args, **kwargs): + def get_user_memberships_with_fines(self, request, pk, *_args, **_kwargs): user = self._get_user(request, pk) self.check_object_permissions(self.request, user) @@ -212,7 +212,7 @@ def get_user_memberships_with_fines(self, request, pk, *args, **kwargs): ) @action(detail=True, methods=["get"], url_path="membership-histories") - def get_user_membership_histories(self, request, pk, *args, **kwargs): + def get_user_membership_histories(self, request, pk, *_args, **_kwargs): user = self._get_user(request, pk) self.check_object_permissions(self.request, user) @@ -225,7 +225,7 @@ def get_user_membership_histories(self, request, pk, *args, **kwargs): context={"request": request}, ) - def post_user_badges(self, request, *args, **kwargs): + def post_user_badges(self, request, *_args, **_kwargs): import uuid user = self.request.user @@ -265,7 +265,7 @@ def post_user_badges(self, request, *args, **kwargs): status=status.HTTP_400_BAD_REQUEST, ) - def get_user_detail_badges(self, request, *args, **kwargs): + def get_user_detail_badges(self, request, *_args, **kwargs): user = self._get_user(request, kwargs["pk"]) user_badges = user.user_badges.order_by("-created_at") badges = [ @@ -289,7 +289,7 @@ def get_or_post_detail_user_badges(self, request, *args, **kwargs): return self.post_user_badges(request, *args, **kwargs) @action(detail=False, methods=["get"], url_path="me/strikes") - def get_user_strikes(self, request, *args, **kwargs): + def get_user_strikes(self, request, *_args, **_kwargs): strikes = request.user.strikes.active() serializer = UserInfoStrikeSerializer( instance=strikes, many=True, context={"request": request} @@ -297,7 +297,7 @@ def get_user_strikes(self, request, *args, **kwargs): return Response(serializer.data, status=status.HTTP_200_OK) @action(detail=True, methods=["get"], url_path="strikes") - def get_user_detail_strikes(self, request, *args, **kwargs): + def get_user_detail_strikes(self, request, *_args, **_kwargs): user = self.get_object() strikes = user.strikes.active() serializer = UserInfoStrikeSerializer( @@ -306,7 +306,7 @@ def get_user_detail_strikes(self, request, *args, **kwargs): return Response(serializer.data, status=status.HTTP_200_OK) @action(detail=False, methods=["get"], url_path="me/events") - def get_user_events(self, request, *args, **kwargs): + def get_user_events(self, request, *_args, **_kwargs): filter_field = self.request.query_params.get("expired") event_has_ended = CaseInsensitiveBooleanQueryParam(filter_field).value @@ -326,7 +326,7 @@ def get_user_events(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"], url_path="me/forms") - def get_user_forms(self, request, *args, **kwargs): + def get_user_forms(self, request, *_args, **_kwargs): forms = request.user.forms filter_field = request.query_params.get("unanswered") @@ -347,7 +347,7 @@ def get_user_forms(self, request, *args, **kwargs): url_path="activate", permission_classes=(IsHS | IsDev,), ) - def makeTIHLDEMember(self, request, *args, **kwargs): + def makeTIHLDEMember(self, request, *_args, **_kwargs): TIHLDE = Group.objects.get(slug=Groups.TIHLDE) user_id = request.data["user_id"] user = get_object_or_404(User, user_id=user_id) @@ -372,7 +372,7 @@ def makeTIHLDEMember(self, request, *args, **kwargs): url_path="decline", permission_classes=(IsHS | IsDev,), ) - def declineTIHLDEMember(self, request, *args, **kwargs): + def declineTIHLDEMember(self, request, *_args, **_kwargs): user_id = request.data["user_id"] try: reason = request.data["reason"] @@ -397,7 +397,7 @@ def declineTIHLDEMember(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"], url_path="me/data") - def export_user_data(self, request, *args, **kwargs): + def export_user_data(self, request, *_args, **_kwargs): export_successfull = export_user_data(request, request.user) if export_successfull: @@ -414,7 +414,7 @@ def export_user_data(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"], url_path="me/reservations") - def get_user_reservations(self, request, *args, **kwargs): + def get_user_reservations(self, request, *_args, **_kwargs): user = request.user reservations = Reservation.objects.filter(author=user).order_by("start_time") serializer = ReservationSerializer( diff --git a/app/content/views/user_bio.py b/app/content/views/user_bio.py index fcb7da4c0..5eeb1081d 100644 --- a/app/content/views/user_bio.py +++ b/app/content/views/user_bio.py @@ -50,5 +50,5 @@ def update(self, request, *args, **kwargs): def destroy(self, request, *args, **kwargs): super().destroy(request, *args, **kwargs) return Response( - {"detail": ("Brukerbio ble slettet")}, status=status.HTTP_200_OK + {"detail": "Brukerbio ble slettet"}, status=status.HTTP_200_OK ) diff --git a/app/content/views/user_calendar_events.py b/app/content/views/user_calendar_events.py index fd480a5bf..3c26c72ff 100644 --- a/app/content/views/user_calendar_events.py +++ b/app/content/views/user_calendar_events.py @@ -22,7 +22,8 @@ def __call__(self, request, *args, **kwargs): if not self.user.public_event_registrations: return JsonResponse( { - "detail": "Denne brukeren har skrudd av offentlig deling av påmeldinger til arrangementer. Du kan derfor ikke hente ut brukerens arrangementer som .ics-fil" + "detail": "Denne brukeren har skrudd av offentlig deling av påmeldinger til arrangementer. " + "Du kan derfor ikke hente ut brukerens arrangementer som .ics-fil" }, status=status.HTTP_403_FORBIDDEN, ) diff --git a/app/emoji/views/reaction.py b/app/emoji/views/reaction.py index 518364df2..38c19f2ef 100644 --- a/app/emoji/views/reaction.py +++ b/app/emoji/views/reaction.py @@ -31,7 +31,7 @@ def update(self, request, *args, **kwargs): reaction, data=request.data, context={"request": request} ) if serializer.is_valid(): - reaction = super().perform_update(serializer) + super().perform_update(serializer) return Response(serializer.data, status=status.HTTP_200_OK) def destroy(self, request, *args, **kwargs): diff --git a/app/forms/models/forms.py b/app/forms/models/forms.py index 642654ec8..737fb84e7 100644 --- a/app/forms/models/forms.py +++ b/app/forms/models/forms.py @@ -64,7 +64,7 @@ def has_retrieve_permission(cls, request): return True @classmethod - def has_statistics_permission(cls, request): + def has_statistics_permission(cls, _request): return True def has_object_statistics_permission(self, request): diff --git a/app/forms/views/form.py b/app/forms/views/form.py index 09ec32a4a..a5b75cfd9 100644 --- a/app/forms/views/form.py +++ b/app/forms/views/form.py @@ -52,7 +52,7 @@ def destroy(self, request, *args, **kwargs): return Response({"detail": "Skjemaet ble slettet"}, status=status.HTTP_200_OK) @action(detail=True, methods=["get"], url_path="statistics") - def statistics(self, request, *args, **kwargs): + def statistics(self, _request, *_args, **_kwargs): form = self.get_object() serializer = FormStatisticsSerializer(form) return Response(serializer.data, status=status.HTTP_200_OK) diff --git a/app/forms/views/submission.py b/app/forms/views/submission.py index b148a2126..0333d71c0 100644 --- a/app/forms/views/submission.py +++ b/app/forms/views/submission.py @@ -68,6 +68,6 @@ def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) @action(detail=False, methods=["get"], url_path="download") - def download(self, request, *args, **kwargs): + def download(self, _request, *_args, **_kwargs): """To return the response as csv, include header 'Accept: text/csv.""" return SubmissionsCsvWriter(self.get_queryset()).write_csv() diff --git a/app/gallery/views/picture.py b/app/gallery/views/picture.py index fa3cf5403..7f395e5bf 100644 --- a/app/gallery/views/picture.py +++ b/app/gallery/views/picture.py @@ -36,7 +36,7 @@ def create(self, request, *args, **kwargs): errors = 0 for file in files: try: - url = AzureFileHandler(file).uploadBlob() + url = AzureFileHandler(file).upload_blob() Picture.objects.create(image=url, album=album) except Exception: errors += 1 diff --git a/app/group/filters/membership.py b/app/group/filters/membership.py index b975bb737..f04548c61 100644 --- a/app/group/filters/membership.py +++ b/app/group/filters/membership.py @@ -16,7 +16,7 @@ class Meta: model = Membership fields = ["onlyMembers"] - def filter_membership_type(self, queryset, name, value): + def filter_membership_type(self, queryset, _name, value): if value: return queryset.filter(membership_type=MembershipType.MEMBER) return queryset diff --git a/app/group/serializers/group.py b/app/group/serializers/group.py index b3ac02146..02c56144b 100644 --- a/app/group/serializers/group.py +++ b/app/group/serializers/group.py @@ -95,7 +95,7 @@ class Meta: model = Group fields = ("studyyears", "studies") - def get_studyyears(self, obj, *args, **kwargs): + def get_studyyears(self, obj, *_args, **_kwargs): return filter( lambda studyyear: studyyear["amount"] > 0, map( @@ -109,7 +109,7 @@ def get_studyyears(self, obj, *args, **kwargs): ), ) - def get_studies(self, obj, *args, **kwargs): + def get_studies(self, obj, *_args, **_kwargs): return filter( lambda study: study["amount"] > 0, map( diff --git a/app/group/views/fine.py b/app/group/views/fine.py index 8b443eaa1..de15f638a 100644 --- a/app/group/views/fine.py +++ b/app/group/views/fine.py @@ -42,6 +42,7 @@ def get_queryset(self): group__slug=self.kwargs["slug"], group__fines_activated=True ) + # noinspection PyShadowingNames def create(self, request, *args, **kwargs): context = { "group_slug": kwargs["slug"], @@ -85,7 +86,7 @@ def destroy(self, request, *args, **kwargs): return Response({"detail": ("Boten ble slettet")}, status=status.HTTP_200_OK) @action(detail=False, methods=["get"], url_path=r"users/(?P[^/.]+)") - def get_user_fines(self, request, *args, **kwargs): + def get_user_fines(self, _request, *_args, **kwargs): """Get the fines of a specific user in a group""" fines = ( @@ -96,7 +97,7 @@ def get_user_fines(self, request, *args, **kwargs): return self.paginate_response(data=fines, serializer=FineNoUserSerializer) @action(detail=False, methods=["get"], url_path="users") - def get_fine_users(self, request, *args, **kwargs): + def get_fine_users(self, _request, *_args, **_kwargs): """Get the users in a group which has fines and how many""" users = self.get_fine_filter_query() return self.paginate_response(data=users, serializer=UserFineSerializer) @@ -119,7 +120,7 @@ def get_fine_filter_query(self): ) @action(detail=False, methods=["put"], url_path="batch-update") - def batch_update_fines(self, request, *args, **kwargs): + def batch_update_fines(self, request, *_args, **_kwargs): """Update a batch of fines at once""" assert request.data["data"] fines = self.get_queryset().filter(id__in=request.data["fine_ids"]) @@ -140,7 +141,7 @@ def batch_update_fines(self, request, *args, **kwargs): ) @action(detail=False, methods=["put"], url_path=r"batch-update/(?P[^/.]+)") - def batch_update_user_fines(self, request, *args, **kwargs): + def batch_update_user_fines(self, request, *_args, **kwargs): """Update all the fines of a user in a specific group""" fines = self.get_queryset().filter(user__user_id=kwargs["user_id"]) serializer = FineUpdateCreateSerializer( @@ -160,12 +161,12 @@ def batch_update_user_fines(self, request, *args, **kwargs): ) @action(detail=False, methods=["get"], url_path="statistics") - def get_group_fine_statistics(self, request, *args, **kwargs): + def get_group_fine_statistics(self, _request, *_args, **kwargs): group = Group.objects.get(slug=kwargs["slug"]) return Response(FineStatisticsSerializer(group).data, status=status.HTTP_200_OK) @action(detail=True, methods=["put"], url_path="defense") - def update_defense(self, request, *args, **kwargs): + def update_defense(self, request, *_args, **_kwargs): fine = self.get_object() serializer = FineUpdateDefenseSerializer( fine, data=request.data, context={"request": request} diff --git a/app/group/views/group.py b/app/group/views/group.py index 80e24f399..a96f19cea 100644 --- a/app/group/views/group.py +++ b/app/group/views/group.py @@ -80,7 +80,7 @@ def create(self, request, *args, **kwargs): ) @action(detail=True, methods=["get"], url_path="statistics") - def statistics(self, request, *args, **kwargs): + def statistics(self, request, *_args, **_kwargs): group = self.get_object() serializer = GroupStatisticsSerializer(group, context={"request": request}) return Response(serializer.data, status=status.HTTP_200_OK) diff --git a/app/group/views/law.py b/app/group/views/law.py index 62786c350..83228bf9d 100644 --- a/app/group/views/law.py +++ b/app/group/views/law.py @@ -32,4 +32,4 @@ def create(self, request, *args, **kwargs): def destroy(self, request, *args, **kwargs): super().destroy(request, *args, **kwargs) - return Response({"detail": ("Loven ble slettet")}, status=status.HTTP_200_OK) + return Response({"detail": "Loven ble slettet"}, status=status.HTTP_200_OK) diff --git a/app/group/views/membership.py b/app/group/views/membership.py index 8b7ff0411..1e4356a8e 100644 --- a/app/group/views/membership.py +++ b/app/group/views/membership.py @@ -57,9 +57,14 @@ def update(self, request, *args, **kwargs): f"Du er nå leder i {membership.group.name}", UserNotificationSettingType.GROUP_MEMBERSHIP, ).add_paragraph(f"Hei, {membership.user.first_name}!").add_paragraph( - f'Du har blitt gjort til leder i gruppen "{membership.group.name}". Som leder får du tilgang til diverse funksjonalitet på nettsiden. Du kan finne administrasjonspanelene du har tilgang til under "Admin" i din profil.' + f'Du har blitt gjort til leder i gruppen "{membership.group.name}". Som leder får du tilgang til ' + f'diverse funksjonalitet på nettsiden. Du kan finne administrasjonspanelene du har tilgang til ' + f'under "Admin" i din profil.' ).add_paragraph( - f'Som leder har du også fått administratorrettigheter i "{membership.group.name}". Det innebærer at du kan legge til og fjerne medlemmer, endre tidligere medlemskap og administrere gruppens spørreskjemaer. I gruppens innstillinger kan du endre gruppens beskrivelse og logo, samt aktivere botsystemet og velge en botsjef.' + f'Som leder har du også fått administratorrettigheter i "{membership.group.name}". Det innebærer ' + f'at du kan legge til og fjerne medlemmer, endre tidligere medlemskap og administrere gruppens ' + f'spørreskjemaer. I gruppens innstillinger kan du endre gruppens beskrivelse og logo, samt ' + f'aktivere botsystemet og velge en botsjef.' ).add_paragraph( "Gratulerer så mye og lykke til med ledervervet!" ).add_link( @@ -87,7 +92,9 @@ def create(self, request, *args, **kwargs): admin_text = " " if group.type in [GroupType.BOARD, GroupType.SUBGROUP]: - admin_text = f'Som medlem av "{group.name}" har du også fått tilgang til diverse funksjonalitet på nettsiden. Du kan finne administrasjonspanelene du har tilgang til under "Admin" i din profil. ' + admin_text = (f'Som medlem av "{group.name}" har du også fått tilgang til diverse funksjonalitet på ' + f'nettsiden. Du kan finne administrasjonspanelene du har tilgang til under "Admin" ' + f'i din profil. ') Notify( [membership.user], diff --git a/app/payment/models/order.py b/app/payment/models/order.py index dd2214675..e82fc55e2 100644 --- a/app/payment/models/order.py +++ b/app/payment/models/order.py @@ -75,10 +75,10 @@ def has_list_permission(cls, request): def has_read_all_permission(cls, request): return is_admin_user(request) - def has_object_update_permission(self, request): + def has_object_update_permission(self, _request): return False - def has_object_destroy_permission(self, request): + def has_object_destroy_permission(self, _request): return False def has_object_retrieve_permission(self, request): diff --git a/app/payment/tasks.py b/app/payment/tasks.py index 26e13fab9..f41386c22 100644 --- a/app/payment/tasks.py +++ b/app/payment/tasks.py @@ -7,7 +7,7 @@ @app.task(bind=True, base=BaseTask) -def check_if_has_paid(self, event_id, registration_id): +def check_if_has_paid(_self, event_id, registration_id): registration = Registration.objects.filter(registration_id=registration_id).first() event = Event.objects.filter(id=event_id).first() diff --git a/app/payment/util/payment_utils.py b/app/payment/util/payment_utils.py index e7e2f6118..b3bd93677 100644 --- a/app/payment/util/payment_utils.py +++ b/app/payment/util/payment_utils.py @@ -26,7 +26,7 @@ def get_new_access_token(): response = response.json() - return (response["expires_on"], response["access_token"]) + return response["expires_on"], response["access_token"] def check_access_token(): diff --git a/app/payment/views/vipps_callback.py b/app/payment/views/vipps_callback.py index 754564d79..f0224ff42 100644 --- a/app/payment/views/vipps_callback.py +++ b/app/payment/views/vipps_callback.py @@ -19,4 +19,4 @@ def force_payment(order_id): res = requests.post(url, headers=headers) status_code = res.status_code json = res.json() - return (json, status_code) + return json, status_code diff --git a/app/util/export_user_data.py b/app/util/export_user_data.py index b8fb2f74b..cdfda0fbf 100644 --- a/app/util/export_user_data.py +++ b/app/util/export_user_data.py @@ -104,8 +104,6 @@ def export_user_data(request, user): mails = MailGDPRSerializer(user.emails, many=True, context={"request": request}) data["eposter"] = mails.data - is_success = False - with tempfile.NamedTemporaryFile() as tmp: with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as archive: for model, json in data.items(): diff --git a/app/util/migrations.py b/app/util/migrations.py index 99dd1698b..087c25ab0 100644 --- a/app/util/migrations.py +++ b/app/util/migrations.py @@ -22,7 +22,7 @@ class UpdateContentType(migrations.RunPython): def _update_contenttype_func( self, old_app: str, old_model: str, new_app: str, new_model: str ): - def func(apps, schema_editor): + def func(_apps, _schema_editor): ContentType.objects.filter(app_label=old_app, model=old_model).update( app_label=new_app, model=new_model ) diff --git a/app/util/utils.py b/app/util/utils.py index 4260acac1..19908b342 100644 --- a/app/util/utils.py +++ b/app/util/utils.py @@ -9,7 +9,7 @@ logger = logging.getLogger(__name__) -def getTimezone(): +def get_timezone(): return pytz_timezone(settings.TIME_ZONE) @@ -18,7 +18,7 @@ def yesterday(): def now(): - return datetime.now(tz=getTimezone()) + return datetime.now(tz=get_timezone()) def tomorrow():