Skip to content

Commit 8e44668

Browse files
16145 Use module.ScriptName to call Script API instead of PK (netbox-community#16170)
* 16145 script api use module.script name instead of pk * 16145 fix test * 16145 allow both pk and script name * 16145 update doc string * Simplify retrieval logic --------- Co-authored-by: Jeremy Stretch <[email protected]>
1 parent 83d3de2 commit 8e44668

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

netbox/extras/api/views.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from django.http import Http404
12
from django.shortcuts import get_object_or_404
23
from django_rq.queues import get_connection
34
from rest_framework import status
@@ -215,21 +216,32 @@ class ScriptViewSet(ModelViewSet):
215216
_ignore_model_permissions = True
216217
lookup_value_regex = '[^/]+' # Allow dots
217218

219+
def _get_script(self, pk):
220+
# If pk is numeric, retrieve script by ID
221+
if pk.isnumeric():
222+
return get_object_or_404(self.queryset, pk=pk)
223+
224+
# Default to retrieval by module & name
225+
try:
226+
module_name, script_name = pk.split('.', maxsplit=1)
227+
except ValueError:
228+
raise Http404
229+
return get_object_or_404(self.queryset, module__file_path=f'{module_name}.py', name=script_name)
230+
218231
def retrieve(self, request, pk):
219-
script = get_object_or_404(self.queryset, pk=pk)
232+
script = self._get_script(pk)
220233
serializer = serializers.ScriptDetailSerializer(script, context={'request': request})
221234

222235
return Response(serializer.data)
223236

224237
def post(self, request, pk):
225238
"""
226-
Run a Script identified by the id and return the pending Job as the result
239+
Run a Script identified by its numeric PK or module & name and return the pending Job as the result
227240
"""
228-
229241
if not request.user.has_perm('extras.run_script'):
230242
raise PermissionDenied("This user does not have permission to run scripts.")
231243

232-
script = get_object_or_404(self.queryset, pk=pk)
244+
script = self._get_script(pk)
233245
input_serializer = serializers.ScriptInputSerializer(
234246
data=request.data,
235247
context={'script': script}

0 commit comments

Comments
 (0)