Coverage for apis_core/apis_entities/urls.py: 64%

25 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-22 07:51 +0000

1from django.contrib.contenttypes.models import ContentType 

2from django.http import Http404 

3from django.shortcuts import get_list_or_404 

4from django.urls import include, path, register_converter 

5 

6from apis_core.apis_entities.api_views import GetEntityGeneric, ListEntityGeneric 

7 

8# from .views import ReversionCompareView TODO: add again when import is fixed 

9from apis_core.apis_entities.models import AbstractEntity 

10from apis_core.apis_entities.views import ( 

11 EntitiesAutocomplete, 

12 EntitiesDuplicate, 

13 EntitiesMerge, 

14) 

15 

16api_routes = [ 

17 path("entities/", ListEntityGeneric.as_view()), 

18 path( 

19 "entity/<int:pk>/", 

20 GetEntityGeneric.as_view(), 

21 name="GetEntityGeneric", 

22 ), 

23] 

24 

25 

26class EntityToContenttypeConverter: 

27 """ 

28 A converter that converts from a the name of an entity class 

29 (i.e. `person`) to the actual Django model class. 

30 """ 

31 

32 regex = r"\w+" 

33 

34 def to_python(self, value): 

35 candiates = get_list_or_404(ContentType, model=value) 

36 candiates = list( 

37 filter( 

38 lambda ct: ct.model_class() is not None 

39 and issubclass(ct.model_class(), AbstractEntity), 

40 candiates, 

41 ) 

42 ) 

43 if len(candiates) > 1: 

44 raise Http404("Multiple entities match the <%s> identifier" % value) 

45 return candiates[0] 

46 

47 def to_url(self, value): 

48 if isinstance(value, ContentType): 

49 return value.model 

50 if isinstance(value, str): 

51 return value 

52 

53 

54register_converter(EntityToContenttypeConverter, "entitytocontenttype") 

55 

56app_name = "apis_entities" 

57 

58entity_patterns = [ 

59 path( 

60 "<int:pk>/duplicate/", 

61 EntitiesDuplicate.as_view(), 

62 name="generic_entities_duplicate_view", 

63 ), 

64 path( 

65 "<int:pk>/merge/", 

66 EntitiesMerge.as_view(), 

67 name="generic_entities_merge_view", 

68 ), 

69] 

70 

71urlpatterns = [ 

72 path( 

73 "entity/<entitytocontenttype:contenttype>/", 

74 include(entity_patterns), 

75 ), 

76 path("autocomplete/", EntitiesAutocomplete.as_view(), name="autocomplete"), 

77]