Coverage for apis_core/generic/routers.py: 57%

14 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2024-12-20 09:24 +0000

1from django.contrib.contenttypes.models import ContentType 

2from rest_framework.reverse import reverse 

3from rest_framework.routers import APIRootView, DefaultRouter 

4 

5from apis_core.generic.abc import GenericModel 

6 

7 

8class CustomAPIRootView(APIRootView): 

9 """ 

10 The default basic root view for CustomDefaultRouter 

11 

12 This view lists the output of the default APIRootView of the Django Rest Framework. 

13 In addition, it injects the routes of the genericmodelapi (those are not hardcoded 

14 registered but autogenerated based on the models that inherit from GenericModel). 

15 """ 

16 

17 def get(self, request, *args, **kwargs): 

18 response = super().get(request, *args, **kwargs) 

19 for content_type in ContentType.objects.all(): 

20 if content_type.model_class() is not None and issubclass( 

21 content_type.model_class(), GenericModel 

22 ): 

23 route = "apis_core:generic:genericmodelapi-list" 

24 response.data[reverse(route, args=[content_type]).strip("/")] = reverse( 

25 route, 

26 args=[content_type], 

27 kwargs=kwargs, 

28 request=request, 

29 format=kwargs.get("format"), 

30 ) 

31 return response 

32 

33 

34class CustomDefaultRouter(DefaultRouter): 

35 """ 

36 The CustomDefaultRouter only diverts from the Django Rest Framework DefaultRouter 

37 by setting the APIRootView to our CustomAPIRootView. 

38 """ 

39 

40 APIRootView = CustomAPIRootView