Skip to content
Open
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: 2 additions & 0 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import contextlib
import datetime
import decimal
import sys

from django import forms
Expand Down Expand Up @@ -927,6 +928,7 @@ def ignore_aliases(self, data):
return True
Dumper.add_representer(SafeString, Dumper.represent_str)
Dumper.add_representer(datetime.timedelta, encoders.CustomScalar.represent_timedelta)
Dumper.add_representer(decimal.Decimal, encoders.CustomScalar.represent_decimal)
return yaml.dump(data, default_flow_style=False, sort_keys=False, Dumper=Dumper).encode('utf-8')


Expand Down
14 changes: 12 additions & 2 deletions rest_framework/utils/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,20 @@ def default(self, obj):

class CustomScalar:
"""
CustomScalar that knows how to encode timedelta that renderer
can understand.
CustomScalar that knows how to encode timedelta and Decimal values
that renderer can understand.
"""
@classmethod
def represent_timedelta(cls, dumper, data):
value = str(data.total_seconds())
return dumper.represent_scalar('tag:yaml.org,2002:str', value)

@classmethod
def represent_decimal(cls, dumper, data):
# Render the exact value as a number: OpenAPI needs numbers for
# keywords such as `maximum`, and a float could round the value.
if not data.is_finite():
return dumper.represent_float(float('nan') if data.is_nan() else float(data))
value = format(data, 'f')
tag = 'tag:yaml.org,2002:float' if '.' in value else 'tag:yaml.org,2002:int'
return dumper.represent_scalar(tag, value)
20 changes: 20 additions & 0 deletions tests/schemas/test_openapi.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import uuid
import warnings
from decimal import Decimal

import pytest
from django.db import models
Expand Down Expand Up @@ -1289,6 +1290,25 @@ def test_schema_rendering_timedelta_to_yaml_with_validator(self):
assert b"openapi: " in ret
assert b"duration:\n type: string\n minimum: \'10.0\'\n" in ret

def test_schema_rendering_decimal_to_yaml_with_validator(self):
patterns = [
path('example/', views.ExampleValidatedAPIView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)

request = create_request('/')
schema = generator.get_schema(request=request)
ret = OpenAPIRenderer().render(schema)
assert b"!!python" not in ret
assert b"maximum: 500\n minimum: 0.01\n" in ret

def test_schema_rendering_decimal_to_yaml_keeps_exact_value(self):
ret = OpenAPIRenderer().render({
'maximum': Decimal('0.12345678901234567890'),
'minimum': Decimal('-1E+400'),
})
assert ret == b"maximum: 0.12345678901234567890\nminimum: -1" + b"0" * 400 + b"\n"

def test_schema_with_no_paths(self):
patterns = []
generator = SchemaGenerator(patterns=patterns)
Expand Down
8 changes: 8 additions & 0 deletions tests/schemas/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import uuid
from datetime import timedelta
from decimal import Decimal

from django.core.validators import (
DecimalValidator, MaxLengthValidator, MaxValueValidator,
Expand Down Expand Up @@ -139,6 +140,13 @@ class ExampleValidatedSerializer(serializers.Serializer):
MinValueValidator(timedelta(seconds=10)),
)
)
price = serializers.DecimalField(
max_digits=6, decimal_places=2,
validators=(
MaxValueValidator(Decimal('500')),
MinValueValidator(Decimal('0.01')),
)
)


class ExampleValidatedAPIView(generics.GenericAPIView):
Expand Down