Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

from collections import Counter 

 

from backend_app.models.abstract.base import BaseModelViewSet 

from backend_app.models.abstract.versionedEssentialModule import ( 

VersionedEssentialModule, 

) 

from backend_app.permissions.utils import Request, FakeUser 

 

 

def check_viewsets(all_viewsets): 

""" 

This function performs multiple checks on the viewsets to make sure they are well configured. 

 

First for all types of viewsets. 

Check 1: all viewsets have an end_point_route attribute 

Check 2: all viewsets have working permissions classes 

See: https://rex-dri.gitlab.utc.fr/rex-dri/documentation/#/Application/Backend/models_serializers_viewsets?id=viewsets 

 

Then for REST enpoints: 

Check 3: 

Check that if 2 serializers are registered for the same model. Then that model 

has a get_serializer method to point to the serializer to use to deserialize it. 

There should be only one of serializer being used per model. Otherwise extra 

configuration is required. 

""" 

 

# Check 1 

for v in all_viewsets: 

if v.end_point_route is None: 

raise Exception( 

"You forget to configure the `end_point_route` " 

"attribute in the viewset {}".format(v) 

) 

 

# Check 2 

fake_request = Request(FakeUser(["DRI"]), "PUT") 

for v in all_viewsets: 

try: 

for p in v().get_permissions(): 

p.has_permission(fake_request, None) 

except TypeError: 

raise Exception( 

"`permission_classes` on viewset {} are misconfigured.\n" 

"Have a look at the documentation: " 

"https://rex-dri.gitlab.utc.fr/rex-dri/documentation/#/Application/Backend/models_serializers_viewsets?id=viewsets".format( 

v 

) 

) 

 

# Check 3 

serializers = list() 

models = [] 

for v in filter(lambda v: issubclass(v, BaseModelViewSet), all_viewsets): 

serializer = v().get_serializer_class() 

model = serializer.Meta.model 

 

if issubclass(model, VersionedEssentialModule): 

if serializer not in serializers: 

serializers.append(serializer) 

models.append(model) 

 

models = dict(Counter(models)) 

for model, n in models.items(): 

if n > 1: 

try: 

# Check that the model has a get_serializer method 

model.get_serializer() 

 

except AttributeError: 

raise Exception( 

"The model {} has multiple serializers pointing to it. " 

"In such case, you must define the get_serializer method inside the model. " 

"Have a look at the documentation.".format(model) 

)