Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Fix more wrong types in the generated schema for serializer fields

Roland Geiderd06e73bf5379
diff --git a/wger/core/api/views.py b/wger/core/api/views.py
index 804f9df68..4f0cbe7c4 100644
--- a/wger/core/api/views.py
+++ b/wger/core/api/views.py
@@ -57,6 +57,9 @@ from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.fields import (
BooleanField,
CharField,
+ DictField,
+ JSONField,
+ ListField,
)
from rest_framework.permissions import (
AllowAny,
@@ -359,6 +362,19 @@ class RoutineWeightUnitViewSet(viewsets.ReadOnlyModelViewSet):
filterset_fields = ('name',)
+@extend_schema(
+ request=LanguageCheckSerializer,
+ responses={
+ 200: inline_serializer(
+ name='LanguageCheckResponse',
+ fields={'result': BooleanField()},
+ ),
+ 400: OpenApiResponse(
+ description='The input could not be detected as the given language, '
+ 'or the language itself is unknown'
+ ),
+ },
+)
@api_view(['POST'])
def check_language(request):
"""
@@ -370,6 +386,15 @@ def check_language(request):
return Response({'result': True})
+@extend_schema(
+ request=None,
+ responses={
+ 200: inline_serializer(
+ name='RefreshTokenResponse',
+ fields={'refresh_token': CharField()},
+ ),
+ },
+)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def issue_refresh_token(request):
@@ -388,6 +413,17 @@ def issue_refresh_token(request):
return Response({'refresh_token': refresh_token})
+@extend_schema(
+ responses={
+ 200: inline_serializer(
+ name='PowersyncTokenResponse',
+ fields={
+ 'token': CharField(),
+ 'powersync_url': CharField(),
+ },
+ ),
+ },
+)
@api_view()
@permission_classes([IsAuthenticated])
def get_powersync_token(request):
@@ -406,11 +442,47 @@ def get_powersync_token(request):
)
+@extend_schema(
+ responses={
+ 200: inline_serializer(
+ name='PowersyncKeysResponse',
+ # A JWKS document. Left as free-form objects on purpose, the exact
+ # members depend on the configured key and are consumed by a JWT
+ # library rather than read field by field.
+ fields={'keys': ListField(child=DictField())},
+ ),
+ },
+)
@api_view()
def get_powersync_keys(request):
return JsonResponse({'keys': [powersync.public_jwk()]})
+@extend_schema(
+ # COMPONENT_SPLIT_REQUEST appends "Request" to the name, so don't repeat it
+ request=inline_serializer(
+ name='PowersyncUpload',
+ fields={
+ 'table': CharField(),
+ 'data': JSONField(),
+ },
+ ),
+ responses={
+ # A permanent refusal stays 200 with an `error` key, because powersync
+ # treats any non-2xx as "retry" and would otherwise loop forever.
+ 200: inline_serializer(
+ name='PowersyncUploadResponse',
+ fields={
+ 'status': CharField(required=False),
+ 'error': CharField(required=False),
+ 'details': CharField(required=False),
+ },
+ ),
+ 403: OpenApiResponse(description='The request is not authenticated'),
+ 500: OpenApiResponse(description='Unclassified server error, the client should retry'),
+ 503: OpenApiResponse(description='Transient database error, the client should retry'),
+ },
+)
@api_view(['PUT', 'PATCH', 'DELETE'])
def upload_powersync_data(request):
if not request.user.is_authenticated:
diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py
index 9a72c17a0..aec3befb8 100644
--- a/wger/exercises/api/serializers.py
+++ b/wger/exercises/api/serializers.py
@@ -30,11 +30,13 @@ from django.db.models.functions import Length
# Third Party
from actstream import action as actstream_action
+from drf_spectacular.utils import extend_schema_field
from easy_thumbnails.exceptions import InvalidImageFormatError
from easy_thumbnails.files import get_thumbnailer
from rest_framework import serializers
# wger
+from wger.core.api.serializers import LicenseSerializer
from wger.core.models import License
from wger.exercises.api.validators import validate_language_matches
from wger.exercises.models import (
@@ -50,6 +52,7 @@ from wger.exercises.models import (
Translation,
)
from wger.exercises.views.helper import StreamVerbs
+from wger.utils.api_schema import ThumbnailsSerializer
from wger.utils.cache import CacheKeyMapper
from wger.utils.constants import CC_BY_SA_4_LICENSE_ID
from wger.utils.db import is_postgres_db
@@ -225,6 +228,7 @@ class ExerciseImageSerializer(serializers.ModelSerializer):
'is_ai_generated',
)
+ @extend_schema_field(ThumbnailsSerializer(allow_null=True))
def get_thumbnails(self, obj: ExerciseImage):
if not obj.image:
return None
@@ -394,11 +398,11 @@ class MuscleSerializer(serializers.ModelSerializer):
'image_url_secondary',
)
- def get_image_url_main(self, obj: Muscle):
+ def get_image_url_main(self, obj: Muscle) -> str | None:
"""Absolute URL to the main muscle image"""
return make_absolute_url(obj.image_url_main, self.context.get('request'))
- def get_image_url_secondary(self, obj: Muscle):
+ def get_image_url_secondary(self, obj: Muscle) -> str | None:
"""Absolute URL to the secondary muscle image"""
return make_absolute_url(obj.image_url_secondary, self.context.get('request'))
@@ -611,10 +615,12 @@ class ExerciseInfoSerializer(serializers.ModelSerializer):
author_history = serializers.ListSerializer(child=serializers.CharField())
total_authors_history = serializers.ListSerializer(child=serializers.CharField())
last_update_global = serializers.DateTimeField(read_only=True)
+ # Declared explicitly instead of relying on Meta.depth, which would expose
+ # it as an anonymous "Nested" component in the schema.
+ license = LicenseSerializer(read_only=True)
class Meta:
model = Exercise
- depth = 1
fields = (
'id',
'uuid',
diff --git a/wger/nutrition/api/serializers.py b/wger/nutrition/api/serializers.py
index f3081b4c9..73e40c718 100644
--- a/wger/nutrition/api/serializers.py
+++ b/wger/nutrition/api/serializers.py
@@ -20,11 +20,16 @@ import logging
from django.conf import settings
# Third Party
+from drf_spectacular.utils import extend_schema_field
from easy_thumbnails.exceptions import EasyThumbnailsError
from easy_thumbnails.files import get_thumbnailer
from rest_framework import serializers
# wger
+from wger.core.api.serializers import (
+ LanguageSerializer,
+ LicenseSerializer,
+)
from wger.nutrition.models import (
Image,
Ingredient,
@@ -34,6 +39,7 @@ from wger.nutrition.models import (
MealItem,
NutritionPlan,
)
+from wger.utils.api_schema import ThumbnailsSerializer
from wger.utils.url import make_absolute_url
@@ -138,10 +144,14 @@ class IngredientInfoSerializer(serializers.ModelSerializer):
weight_units = IngredientWeightUnitSerializer(source='ingredientweightunit_set', many=True)
image = IngredientImageSerializer(read_only=True)
thumbnails = serializers.SerializerMethodField()
+ # Declared explicitly instead of relying on Meta.depth, which builds an
+ # anonymous nested serializer per relation. Both ended up named "Nested" in
+ # the schema, so language was documented with the license's fields.
+ language = LanguageSerializer(read_only=True)
+ license = LicenseSerializer(read_only=True)
class Meta:
model = Ingredient
- depth = 1
fields = (
'id',
'uuid',
@@ -178,6 +188,7 @@ class IngredientInfoSerializer(serializers.ModelSerializer):
'thumbnails',
)
+ @extend_schema_field(ThumbnailsSerializer(allow_null=True))
def get_thumbnails(self, obj: Ingredient):
if not hasattr(obj, 'image'):
return None
diff --git a/wger/trophies/api/serializers.py b/wger/trophies/api/serializers.py
index bf5e073e2..942bdc4f8 100644
--- a/wger/trophies/api/serializers.py
+++ b/wger/trophies/api/serializers.py
@@ -62,15 +62,15 @@ class TrophySerializer(serializers.ModelSerializer):
)
read_only_fields = fields
- def get_name(self, obj: Trophy):
+ def get_name(self, obj: Trophy) -> str:
"""Translate the trophy name"""
return _(obj.name)
- def get_description(self, obj: Trophy):
+ def get_description(self, obj: Trophy) -> str:
"""Translate the trophy description"""
return _(obj.description)
- def get_image(self, obj: Trophy):
+ def get_image(self, obj: Trophy) -> str | None:
"""Build absolute URL to trophy image, if possible."""
request = self.context.get('request')
diff --git a/wger/utils/api_schema.py b/wger/utils/api_schema.py
new file mode 100644
index 000000000..61cda7e07
--- /dev/null
+++ b/wger/utils/api_schema.py
@@ -0,0 +1,29 @@
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+# Third Party
+from rest_framework import serializers
+
+
+class ThumbnailsSerializer(serializers.Serializer):
+ """
+ Shape of the ``thumbnails`` field, used for schema generation only.
+
+ The aliases are read from settings.THUMBNAIL_ALIASES and are the same for
+ every thumbnailed image in the API. Without this, the generated schema falls
+ back to a plain string for the dict the method fields return.
+ """
+
+ small = serializers.URLField()
+ medium = serializers.URLField()