Skip to content

Commit

Permalink
format: reformat codebase, fix ruff lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
m4tx committed Nov 26, 2023
1 parent c618dc1 commit c6eea47
Show file tree
Hide file tree
Showing 51 changed files with 424 additions and 472 deletions.
21 changes: 12 additions & 9 deletions admin/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,27 @@


class Kcc3AdminSite(admin.AdminSite):
index_title = 'Home'
index_title = "Home"

def get_app_list(self, request):
apps = super().get_app_list(request)

grouped_apps = ('badges', 'chombos', 'players', 'yakumans')
group_filter = lambda x: x['app_label'] in grouped_apps
grouped_apps = ("badges", "chombos", "players", "yakumans")

def group_filter(x):
return x["app_label"] in grouped_apps

first_party = filter(group_filter, apps)
third_party = itertools.filterfalse(group_filter, apps)

models = list(itertools.chain(*map(lambda x: x['models'], first_party)))
models = list(itertools.chain(*(x["models"] for x in first_party)))

kcc3_app = {
'name': 'Mahjong',
'app_label': 'kcc3',
'app_url': '',
'has_module_perms': True,
'models': models,
"name": "Mahjong",
"app_label": "kcc3",
"app_url": "",
"has_module_perms": True,
"models": models,
}

return itertools.chain([kcc3_app], third_party)
2 changes: 1 addition & 1 deletion admin/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


class Kcc3AdminConfig(AdminConfig):
default_site = 'admin.admin.Kcc3AdminSite'
default_site = "admin.admin.Kcc3AdminSite"
64 changes: 33 additions & 31 deletions badges/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from collections.abc import Iterable
from typing import ClassVar

from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.utils.html import format_html
Expand All @@ -6,43 +9,41 @@


class IsAutomaticFilter(SimpleListFilter):
title = 'automatic'
parameter_name = 'automatic'
title = "automatic"
parameter_name = "automatic"

def lookups(self, request, model_admin):
return (
('1', 'Yes'),
('0', 'No'),
("1", "Yes"),
("0", "No"),
)

def queryset(self, request, queryset):
if self.value() == '1':
if self.value() == "1":
return queryset.automatic()
elif self.value() == '0':
elif self.value() == "0":
return queryset.not_automatic()

return queryset


class BadgeAdmin(admin.ModelAdmin):
prepopulated_fields = {'id': ('title',)}
autocomplete_fields = ('owners', 'players')
readonly_fields = ('token',)
prepopulated_fields: ClassVar[dict[str, Iterable[str]]] = {"id": ("title",)}
autocomplete_fields = ("owners", "players")
readonly_fields = ("token",)

list_display = ('image_tag', 'id', 'title', 'automatic', 'description')
list_display_links = ('image_tag', 'id', 'title')
list_filter = ('owners', IsAutomaticFilter)
search_fields = ('id', 'title', 'description')
ordering = ('id',)
list_display = ("image_tag", "id", "title", "automatic", "description")
list_display_links = ("image_tag", "id", "title")
list_filter = ("owners", IsAutomaticFilter)
search_fields = ("id", "title", "description")
ordering = ("id",)

view_on_site = True

def image_tag(self, obj):
return format_html(
f'<img src="{obj.image.url}"'
f' style="max-width: 48px; max-height: 48px;" />')
return format_html(f'<img src="{obj.image.url}"' f' style="max-width: 48px; max-height: 48px;" />')

image_tag.short_description = 'Image'
image_tag.short_description = "Image"

def automatic(self, obj):
return obj.is_automatic
Expand All @@ -57,33 +58,34 @@ def get_queryset(self, request):
return qs.filter(owners=request.user)

def get_fieldsets(self, request, obj=None):
general_fields = ['title', 'id', 'description', 'image']
general_fields = ["title", "id", "description", "image"]
if request.user.is_superuser or obj is not None:
general_fields.append('owners')
general_fields += ['players']
general_fields.append("owners")
general_fields += ["players"]

return (
(None, {
'fields': general_fields
}),
('Endpoint', {
'fields': ('endpoint_url', 'refresh_interval', 'token'),
}),
(None, {"fields": general_fields}),
(
"Endpoint",
{
"fields": ("endpoint_url", "refresh_interval", "token"),
},
),
)

def get_changeform_initial_data(self, request):
return {'owners': (request.user,)}
return {"owners": (request.user,)}

def get_readonly_fields(self, request, obj=None):
fields = super(BadgeAdmin, self).get_readonly_fields(request, obj)
fields = super().get_readonly_fields(request, obj)

if not request.user.is_superuser:
fields = fields + ('owners',)
fields = (*fields, "owners")

return fields

def save_related(self, request, form, formsets, change):
super(BadgeAdmin, self).save_related(request, form, formsets, change)
super().save_related(request, form, formsets, change)

if not form.instance.owners.exists():
form.instance.owners.add(request.user)
Expand Down
2 changes: 1 addition & 1 deletion badges/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


class ApiConfig(AppConfig):
name = 'badges'
name = "badges"
16 changes: 7 additions & 9 deletions badges/local_badge_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from abc import ABC
from typing import Union, List, Iterable
from collections.abc import Iterable

from rest_framework.exceptions import APIException
from rest_framework.status import HTTP_400_BAD_REQUEST
Expand All @@ -9,25 +9,23 @@
from badgeupdater.models import BadgeUpdateRequest
from players.models import Player

PlayerIterable = Iterable[Union[str, Player]]
PlayerIterable = Iterable[str | Player]


class BadgeDoesNotExist(APIException):
status_code = HTTP_400_BAD_REQUEST
default_detail = 'The Badge with given ID does not exist'
default_detail = "The Badge with given ID does not exist"


class LocalBadgeClient(BadgeClient, ABC):
def get_token(self, badge_id: str) -> str:
try:
return Badge.objects.get(id=badge_id).token
except Badge.DoesNotExist:
raise BadgeDoesNotExist
except Badge.DoesNotExist as e:
raise BadgeDoesNotExist from e

def get_badge_player_ids(self, request: BadgeUpdateRequest) -> List[str]:
return list(map(
lambda x: x.id if isinstance(x, Player) else x,
self.get_badge_players(request)))
def get_badge_player_ids(self, request: BadgeUpdateRequest) -> list[str]:
return [x.id if isinstance(x, Player) else x for x in self.get_badge_players(request)]

def get_badge_players(self, request: BadgeUpdateRequest) -> PlayerIterable:
raise NotImplementedError
50 changes: 23 additions & 27 deletions badges/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
from django.db.models import Q
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django_celery_beat.models import PeriodicTask, IntervalSchedule
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from django_hosts import reverse

from badges.token_generator import generate_token, MAX_TOKEN_LENGTH
from badges.token_generator import MAX_TOKEN_LENGTH, generate_token
from badges.validators import (
ImageMinResolutionValidator, ImageMaxResolutionValidator,
MaxFileSizeValidator, image_square_validator)
ImageMaxResolutionValidator,
ImageMinResolutionValidator,
MaxFileSizeValidator,
image_square_validator,
)
from players.models import Player

MIN_RES = settings.BADGE_IMAGE_MIN_RES
Expand All @@ -21,7 +24,7 @@


class BadgeQuerySet(models.QuerySet):
not_automatic_q = Q(endpoint_url__isnull=True) | Q(endpoint_url__exact='')
not_automatic_q = Q(endpoint_url__isnull=True) | Q(endpoint_url__exact="")

def automatic(self):
return self.exclude(self.not_automatic_q)
Expand All @@ -31,30 +34,27 @@ def not_automatic(self):


class Badge(models.Model):
id = models.SlugField(primary_key=True, verbose_name='ID')
id = models.SlugField(primary_key=True, verbose_name="ID")

title = models.CharField(max_length=256)
description = models.TextField(blank=True)
image = models.ImageField(
help_text=f'The image must be square between {MIN_RES}x{MIN_RES} and '
f'{MAX_RES}x{MAX_RES} and must not exceed '
f'{MaxFileSizeValidator.human_readable_size(MAX_SIZE)}.',
help_text=f"The image must be square between {MIN_RES}x{MIN_RES} and "
f"{MAX_RES}x{MAX_RES} and must not exceed "
f"{MaxFileSizeValidator.human_readable_size(MAX_SIZE)}.",
validators=[
ImageMinResolutionValidator(MIN_RES),
ImageMaxResolutionValidator(MAX_RES),
image_square_validator,
MaxFileSizeValidator(MAX_SIZE),
]
],
)
owners = models.ManyToManyField(to=User, blank=True)

endpoint_url = models.URLField(blank=True, verbose_name='Endpoint URL')
endpoint_url = models.URLField(blank=True, verbose_name="Endpoint URL")
refresh_interval = models.DurationField(null=True, blank=True)
token = models.CharField(
blank=True, max_length=MAX_TOKEN_LENGTH, default=generate_token,
editable=False)
periodic_task = models.OneToOneField(
to=PeriodicTask, on_delete=models.CASCADE, null=True, editable=False)
token = models.CharField(blank=True, max_length=MAX_TOKEN_LENGTH, default=generate_token, editable=False)
periodic_task = models.OneToOneField(to=PeriodicTask, on_delete=models.CASCADE, null=True, editable=False)

players = models.ManyToManyField(to=Player, blank=True)

Expand All @@ -65,7 +65,7 @@ def __init__(self, *args, **kwargs):
self.__original_refresh_interval = self.refresh_interval

def get_absolute_url(self):
return reverse('badge-detail', kwargs={'slug': self.id}, host='root')
return reverse("badge-detail", kwargs={"slug": self.id}, host="root")

@property
def is_automatic(self):
Expand All @@ -75,7 +75,7 @@ def save(self, *args, **kwargs):
if self.refresh_interval != self.__original_refresh_interval:
self.__update_task()

super(Badge, self).save(*args, **kwargs)
super().save(*args, **kwargs)

def __update_task(self):
if self.refresh_interval is None and self.periodic_task is not None:
Expand All @@ -85,20 +85,16 @@ def __update_task(self):

def __create_or_update_task_object(self):
if self.periodic_task is None:
kwargs = {
'badge_id': self.id
}
task = PeriodicTask(
task='badgeupdater.server.tasks.update_badge_task',
kwargs=json.dumps(kwargs))
kwargs = {"badge_id": self.id}
task = PeriodicTask(task="badgeupdater.server.tasks.update_badge_task", kwargs=json.dumps(kwargs))
else:
task = self.periodic_task

schedule, _ = IntervalSchedule.objects.get_or_create(
every=round(self.refresh_interval.total_seconds()),
period=IntervalSchedule.SECONDS)
every=round(self.refresh_interval.total_seconds()), period=IntervalSchedule.SECONDS
)
task.interval = schedule
task.name = f'Update {self.id} badge'
task.name = f"Update {self.id} badge"

task.save()
self.periodic_task = task
Expand Down
2 changes: 1 addition & 1 deletion badges/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
class BadgeSerializer(serializers.ModelSerializer):
class Meta:
model = Badge
fields = ['id', 'title', 'description', 'image', 'players']
fields = ("id", "title", "description", "image", "players")
2 changes: 0 additions & 2 deletions badges/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.test import TestCase

# Create your tests here.
14 changes: 6 additions & 8 deletions badges/urls.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
from django.urls import path

from badges.badgeclients import TestBadgeClient
from .views import BadgeDetailView, UpdateBadgeBearersView, BadgeRankingView

from .views import BadgeDetailView, BadgeRankingView, UpdateBadgeBearersView

global_urlpatterns = [
path('', BadgeRankingView.as_view(), name='badge-ranking'),
path("", BadgeRankingView.as_view(), name="badge-ranking"),
]

urlpatterns = [
path('<slug:slug>/', BadgeDetailView.as_view(), name='badge-detail'),
path("<slug:slug>/", BadgeDetailView.as_view(), name="badge-detail"),
]

admin_urlpatters = [
path(
'badge/<slug:slug>/update_bearers/',
UpdateBadgeBearersView.as_view(),
name='update-badge-bearers'),
path("badge/<slug:slug>/update_bearers/", UpdateBadgeBearersView.as_view(), name="update-badge-bearers"),
]

badgeclients_urlpatterns = [
path('test/', TestBadgeClient.as_view()),
path("test/", TestBadgeClient.as_view()),
]
Loading

0 comments on commit c6eea47

Please sign in to comment.