1
1
import json
2
2
import inspect
3
+
3
4
from django .contrib .admindocs .views import simplify_regex
4
5
from django .utils .encoding import force_str
6
+
7
+ from rest_framework .viewsets import ModelViewSet
5
8
from rest_framework .serializers import BaseSerializer
6
9
10
+ VIEWSET_METHODS = {
11
+ 'List' : ['get' , 'post' ],
12
+ 'Instance' : ['get' , 'put' , 'patch' , 'delete' ],
13
+ }
14
+
7
15
8
16
class ApiEndpoint (object ):
9
17
@@ -31,8 +39,14 @@ def __get_path__(self, parent_regex):
31
39
return "/{0}{1}" .format (self .name_parent , simplify_regex (self .pattern .regex .pattern ))
32
40
return simplify_regex (self .pattern .regex .pattern )
33
41
34
- def __get_allowed_methods__ (self ):
42
+ def is_method_allowed (self , callback_cls , method_name ):
43
+ has_attr = hasattr (callback_cls , method_name )
44
+ viewset_method = (issubclass (callback_cls , ModelViewSet ) and
45
+ method_name in VIEWSET_METHODS .get (self .callback .suffix , []))
46
+
47
+ return has_attr or viewset_method
35
48
49
+ def __get_allowed_methods__ (self ):
36
50
viewset_methods = []
37
51
if self .drf_router :
38
52
for prefix , viewset , basename in self .drf_router .registry :
@@ -57,14 +71,18 @@ def __get_allowed_methods__(self):
57
71
)
58
72
if self .pattern .regex .pattern == regex :
59
73
funcs , viewset_methods = zip (
60
- * [(mapping [m ], m .upper ()) for m in self .callback .cls .http_method_names if m in mapping ]
74
+ * [(mapping [m ], m .upper ())
75
+ for m in self .callback .cls .http_method_names
76
+ if m in mapping ]
61
77
)
62
78
viewset_methods = list (viewset_methods )
63
79
if len (set (funcs )) == 1 :
64
80
self .docstring = inspect .getdoc (getattr (self .callback .cls , funcs [0 ]))
65
81
66
- view_methods = [force_str (m ).upper () for m in self .callback .cls .http_method_names if hasattr (self .callback .cls , m )]
67
- return viewset_methods + view_methods
82
+ view_methods = [force_str (m ).upper ()
83
+ for m in self .callback .cls .http_method_names
84
+ if self .is_method_allowed (self .callback .cls , m )]
85
+ return sorted (viewset_methods + view_methods )
68
86
69
87
def __get_docstring__ (self ):
70
88
return inspect .getdoc (self .callback )
0 commit comments