Demo entry 5865345

API

   

Submitted by anonymous on Aug 17, 2016 at 00:06
Language: Python. Code size: 1.5 kB.

# models.py
class Shape(models.Model):
    color = models.CharField(max_length=6)

    class Meta:
        abstract = True


class Circle(Shape):
    radius = models.PositiveIntegerField()

    def area():
        return pi * self.radius**2

    def perimeter():
        return 2 * self.radius * pi


class Rectangle(Shape):
    length = models.PositiveIntegerField()
    width = models.PositiveIntegerField()

    def area():
        return self.length * self.width

    def perimeter():
        return self.length * 2 + self.width * 2



# serializers.py
class ShapeSerializer(serializers.Serializer):
    color = serializers.CharField()
    area = serializers.IntegerField(read_only=True)
    perimeter = serializers.IntegerField(read_only=True)


class CircleSerializer(ShapeSerializer):
    radius = serializers.IntegerField(min_value=0)


class RectangleSerializer(ShapeSerializer):
    length = serializers.IntegerField(min_value=0)
    width = serializers.IntegerField(min_value=0)



# views.py
class CircleViewSet(viewsets.ModelViewSet):
    queryset = Circle.objects.all()
    serializer_class = CircleSerializer


class RectangleViewSet(viewsets.ModelViewSet):
    queryset = Rectangle.objects.all()
    serializer_class = RectangleSerializer



# urls.py
router = DefaultRouter()
router.register(r'circle', CircleViewSet)
router.register(r'rectangle', RectangleViewSet)
urlpatterns = router.urls

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).