Skip to content

Commit 4834bd9

Browse files
Prevent invalid date_format values
1 parent b37056e commit 4834bd9

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

reader/filters.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,15 @@ def to_html(self, *args, **kwargs) -> str:
185185
class DateFormat(BaseFilterBackend):
186186
"""Date format filter."""
187187
description = 'Change the displayed date format.'
188+
_values = ('iso-8601', 'rfc-5322', 'timestamp')
188189

189190
def filter_queryset(self, request: Request, queryset: QuerySet,
190191
view: ViewSet) -> QuerySet:
192+
fmt = request.query_params.get('date_format')
193+
if fmt and fmt not in self._values:
194+
raise ValidationError(detail={
195+
'error': f"Invalid date format: '{fmt}'."
196+
})
191197
return queryset # no actual filtering is performed
192198

193199
def get_schema_operation_parameters(self, view: ViewSet) -> List[Dict]:
@@ -199,7 +205,7 @@ def get_schema_operation_parameters(self, view: ViewSet) -> List[Dict]:
199205
'schema': {
200206
'type': 'string',
201207
'default': 'iso-8601',
202-
'enum': ('iso-8601', 'rfc-5322', 'timestamp')
208+
'enum': self._values
203209
}
204210
}]
205211

reader/serializers.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,13 @@ class ChapterSerializer(ModelSerializer):
6464
def to_representation(self, instance: Chapter) -> Dict:
6565
rep = super().to_representation(instance)
6666
# HACK: adapt the date format based on a query param
67-
dt_format = self.context['request'] \
68-
.query_params.get('date_format', 'iso-8601')
67+
fmt = self.context['request'].query_params.get('date_format')
6968
published = instance.published
7069
rep['published'] = {
7170
'iso-8601': published.strftime('%Y-%m-%dT%H:%M:%SZ'),
7271
'rfc-5322': published.strftime('%a, %d %b %Y %H:%M:%S GMT'),
7372
'timestamp': str(round(published.timestamp() * 1e3))
74-
}.get(dt_format)
73+
}.get(fmt or 'iso-8601')
7574
return rep
7675

7776
def __uri(self, path: str) -> str:

0 commit comments

Comments
 (0)