Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor serializers #391

Merged
merged 6 commits into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pytest-django = "*"
django-cors-headers = "*"
django-debug-toolbar = "*"
django-debug-toolbar-force = "*"
pyyaml = "*"
pyyaml = "~=5.3.1"
uritemplate = "*"
tqdm = "*"
lxml = "*"
Expand Down
498 changes: 229 additions & 269 deletions Pipfile.lock

Large diffs are not rendered by default.

4 changes: 0 additions & 4 deletions apps/core/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ class BoardAdmin(MetaDataModelAdmin):
search_fields = (
"ko_name",
"en_name",
"ko_description",
"en_description",
)


Expand All @@ -63,8 +61,6 @@ class TopicAdmin(MetaDataModelAdmin):
search_fields = (
"ko_name",
"en_name",
"ko_description",
"en_description",
)
list_filter = ("parent_board",)

Expand Down
28 changes: 28 additions & 0 deletions apps/core/migrations/0051_remove_board_en_description_and_more.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 4.2.3 on 2023-07-17 12:52

from django.db import migrations


class Migration(migrations.Migration):
dependencies = [
("core", "0050_board_top_threshold"),
]

operations = [
migrations.RemoveField(
model_name="board",
name="en_description",
),
migrations.RemoveField(
model_name="board",
name="ko_description",
),
migrations.RemoveField(
model_name="topic",
name="en_description",
),
migrations.RemoveField(
model_name="topic",
name="ko_description",
),
]
9 changes: 5 additions & 4 deletions apps/core/models/article.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import typing
from enum import Enum
from typing import Dict, Union

import bs4
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files.storage import default_storage
from django.db import IntegrityError, models, transaction
from django.utils import timezone
Expand All @@ -27,6 +26,8 @@
from .communication_article import SchoolResponseStatus
from .report import Report

User = get_user_model()


class ArticleHiddenReason(str, Enum):
ADULT_CONTENT = "ADULT_CONTENT"
Expand Down Expand Up @@ -261,7 +262,7 @@ def created_by_nickname(self):

# API 상에서 보이는 사용자 (익명일 경우 익명화된 글쓴이, 그 외는 그냥 글쓴이)
@cached_property
def postprocessed_created_by(self) -> Union[settings.AUTH_USER_MODEL, Dict]:
def postprocessed_created_by(self) -> User | dict:
if self.name_type == NameType.REGULAR:
return self.created_by

Expand Down Expand Up @@ -295,7 +296,7 @@ def postprocessed_created_by(self) -> Union[settings.AUTH_USER_MODEL, Dict]:
}

@cache_by_user
def hidden_reasons(self, user: settings.AUTH_USER_MODEL) -> typing.List:
def hidden_reasons(self, user: User) -> list:
reasons = []
if self.is_hidden_by_reported():
reasons.append(ArticleHiddenReason.REPORTED_CONTENT)
Expand Down
6 changes: 0 additions & 6 deletions apps/core/models/board.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,6 @@ class Board(MetaDataModel):
verbose_name="게시판 영문 이름",
max_length=32,
)
ko_description = models.TextField(
verbose_name="게시판 국문 소개",
)
en_description = models.TextField(
verbose_name="게시판 영문 소개",
)
# 사용자 그룹에 대해 접근 권한을 제어하는 bit mask 입니다.
# access_mask & (1 << user.group) > 0 일 때 접근이 가능합니다.
# 사용자 그룹의 값들은 `UserGroup`을 참고하세요.
Expand Down
11 changes: 6 additions & 5 deletions apps/core/models/comment.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import hashlib
import typing
from enum import Enum
from typing import Dict, Union

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files.storage import default_storage
from django.db import IntegrityError, models, transaction
from django.utils import timezone
Expand All @@ -20,6 +19,8 @@
from .board import NameType
from .report import Report

User = get_user_model()


class CommentHiddenReason(Enum):
REPORTED_CONTENT = "REPORTED_CONTENT"
Expand Down Expand Up @@ -166,7 +167,7 @@ def update_report_count(self):

# API 상에서 보이는 사용자 (익명일 경우 익명화된 글쓴이, 그 외는 그냥 글쓴이)
@cached_property
def postprocessed_created_by(self) -> Union[settings.AUTH_USER_MODEL, Dict]:
def postprocessed_created_by(self) -> User | dict:
if self.name_type == NameType.REGULAR:
return self.created_by

Expand Down Expand Up @@ -221,8 +222,8 @@ def postprocessed_created_by(self) -> Union[settings.AUTH_USER_MODEL, Dict]:
}

@cache_by_user
def hidden_reasons(self, user: settings.AUTH_USER_MODEL) -> typing.List:
reasons: typing.List[CommentHiddenReason] = []
def hidden_reasons(self, user: User) -> list[CommentHiddenReason]:
reasons: list[CommentHiddenReason] = []

if self.is_deleted():
reasons.append(CommentHiddenReason.DELETED_CONTENT)
Expand Down
7 changes: 0 additions & 7 deletions apps/core/models/topic.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,6 @@ class Meta(MetaDataModel.Meta):
max_length=32,
verbose_name="말머리 영문 이름",
)
ko_description = models.TextField(
verbose_name="말머리 국문 소개",
)
en_description = models.TextField(
verbose_name="말머리 영문 소개",
)

parent_board = models.ForeignKey(
on_delete=models.CASCADE,
to="core.Board",
Expand Down
13 changes: 6 additions & 7 deletions apps/core/serializers/article.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import typing
from enum import Enum

from django.utils.translation import gettext
Expand Down Expand Up @@ -37,7 +36,7 @@ class Meta:
"migrated_negative_vote_count",
)

def get_my_vote(self, obj) -> typing.Optional[bool]:
def get_my_vote(self, obj) -> bool | None:
request = self.context["request"]
if not obj.vote_set.filter(voted_by=request.user).exists():
return None
Expand All @@ -47,7 +46,7 @@ def get_my_vote(self, obj) -> typing.Optional[bool]:
return my_vote.is_positive

@staticmethod
def get_my_scrap(obj) -> typing.Optional[dict]:
def get_my_scrap(obj) -> dict | None:
from apps.core.serializers.scrap import BaseScrapSerializer

if not obj.scrap_set.exists():
Expand All @@ -57,12 +56,12 @@ def get_my_scrap(obj) -> typing.Optional[dict]:

return BaseScrapSerializer(my_scrap).data

def get_title(self, obj) -> typing.Optional[str]:
def get_title(self, obj) -> str | None:
if self.visible_verdict(obj):
return obj.title
return None

def get_content(self, obj) -> typing.Optional[str]:
def get_content(self, obj) -> str | None:
if self.visible_verdict(obj):
return obj.content
return None
Expand Down Expand Up @@ -99,7 +98,7 @@ def get_read_status(obj) -> str:
return "-"

# TODO: article_current_page property must be cached
def get_article_current_page(self, obj) -> typing.Optional[int]:
def get_article_current_page(self, obj) -> int | None:
view = self.context.get("view")

if view:
Expand Down Expand Up @@ -316,7 +315,7 @@ def get_side_articles_of_recent_article(self, obj, request):
after = None if len(after) == 0 else after[0]
return after, before

def get_attachments(self, obj): # -> typing.Optional[list]:
def get_attachments(self, obj) -> list | None:
if self.visible_verdict(obj):
return obj.attachments.all().values_list("id")
return None
Expand Down
21 changes: 20 additions & 1 deletion apps/core/serializers/board.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,19 @@
class BaseBoardSerializer(MetaDataModelSerializer):
class Meta:
model = Board
fields = "__all__"
fields = [
"id",
"slug",
"ko_name",
"en_name",
"is_readonly",
"name_type",
"group_id",
"banner_image",
"ko_banner_description",
"en_banner_description",
"top_threshold",
]


class BoardSerializer(BaseBoardSerializer):
Expand All @@ -25,6 +37,13 @@ class BoardDetailActionSerializer(BaseBoardSerializer):
user_readable = serializers.SerializerMethodField()
user_writable = serializers.SerializerMethodField()

class Meta(BaseBoardSerializer.Meta):
fields = BaseBoardSerializer.Meta.fields + [
"topics",
"user_readable",
"user_writable",
]

def get_user_readable(self, obj):
user = self.context["request"].user
return obj.group_has_access_permission(
Expand Down
6 changes: 2 additions & 4 deletions apps/core/serializers/comment.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import typing

from rest_framework import serializers

from apps.core.models import Block, Comment, CommentHiddenReason
Expand All @@ -22,15 +20,15 @@ class Meta:
exclude = ("attachment",)

@staticmethod
def get_my_vote(obj) -> typing.Optional[bool]:
def get_my_vote(obj) -> bool | None:
if not obj.vote_set.exists():
return None

my_vote = obj.vote_set.all()[0]

return my_vote.is_positive

def get_content(self, obj) -> typing.Optional[str]:
def get_content(self, obj) -> str | None:
if self.visible_verdict(obj):
return obj.content
return None
Expand Down
8 changes: 3 additions & 5 deletions apps/core/serializers/mixins/hidden.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import typing

from rest_framework import serializers


Expand All @@ -12,11 +10,11 @@ def get_is_mine(self, obj) -> bool:
def get_is_hidden(self, obj) -> bool:
return not self.visible_verdict(obj)

def get_why_hidden(self, obj) -> typing.List[str]:
def get_why_hidden(self, obj) -> list[str]:
_, _, reasons = self.hidden_info(obj)
return [reason.value for reason in reasons]

def get_can_override_hidden(self, obj) -> typing.Optional[bool]:
def get_can_override_hidden(self, obj) -> bool | None:
hidden, can_override, _ = self.hidden_info(obj)
if not hidden:
return
Expand All @@ -33,7 +31,7 @@ def requested_override_hidden(self):
and self.context["override_hidden"] is True
)

def hidden_info(self, obj) -> typing.Tuple[bool, bool, typing.List]:
def hidden_info(self, obj) -> tuple[bool, bool, list]:
user = self.context["request"].user
reasons = obj.hidden_reasons(user)
cannot_override_reasons = [
Expand Down
4 changes: 1 addition & 3 deletions apps/core/serializers/notification.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import typing

from rest_framework import serializers

from apps.core.models import Notification
Expand All @@ -11,7 +9,7 @@ class Meta:
model = Notification
fields = "__all__"

def get_is_read(self, obj) -> typing.Optional[bool]:
def get_is_read(self, obj) -> bool | None:
if not obj.notification_read_log_set.exists():
return None

Expand Down
2 changes: 1 addition & 1 deletion apps/core/serializers/topic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
class BaseTopicSerializer(MetaDataModelSerializer):
class Meta:
model = Topic
fields = "__all__"
fields = ["id", "slug", "ko_name", "en_name"]


class TopicSerializer(BaseTopicSerializer):
Expand Down
4 changes: 1 addition & 3 deletions apps/user/serializers/user_profile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import typing

from dateutil.relativedelta import relativedelta
from django.utils import timezone
from django.utils.translation import gettext
Expand All @@ -18,7 +16,7 @@ class Meta:
fields = "__all__"

@staticmethod
def get_email(obj) -> typing.Optional[str]:
def get_email(obj) -> str | None:
if obj.email.endswith("@sso.sparcs.org"):
return None
return obj.email
Expand Down
Loading