Просмотр исходного кода

Allow running scripts nested in modules/packages

kkthxbye-code 3 лет назад
Родитель
Сommit
f489ffa043

+ 1 - 1
netbox/extras/api/views.py

@@ -257,7 +257,7 @@ class ScriptViewSet(ViewSet):
     lookup_value_regex = '[^/]+'  # Allow dots
 
     def _get_script(self, pk):
-        module_name, script_name = pk.split('.')
+        module_name, script_name = pk.split('.', maxsplit=1)
         script = get_script(module_name, script_name)
         if script is None:
             raise Http404

+ 7 - 1
netbox/extras/scripts.py

@@ -299,6 +299,10 @@ class BaseScript:
     def module(cls):
         return cls.__module__
 
+    @classmethod
+    def root_module(cls):
+        return cls.__module__.split(".")[0]
+
     @classproperty
     def job_timeout(self):
         return getattr(self.Meta, 'job_timeout', None)
@@ -514,7 +518,9 @@ def get_scripts(use_names=False):
         ordered_scripts = [cls for cls in script_order if is_script(cls)]
         unordered_scripts = [cls for _, cls in inspect.getmembers(module, is_script) if cls not in script_order]
         for cls in [*ordered_scripts, *unordered_scripts]:
-            module_scripts[cls.__name__] = cls
+            # For scripts in submodules use the full import path w/o the root module as the name
+            script_name = cls.full_name.split(".", maxsplit=1)[1]
+            module_scripts[script_name] = cls
         if module_scripts:
             scripts[module_name] = module_scripts
 

+ 2 - 2
netbox/extras/urls.py

@@ -1,4 +1,4 @@
-from django.urls import path
+from django.urls import path, re_path
 
 from extras import models, views
 from netbox.views.generic import ObjectChangeLogView
@@ -105,7 +105,7 @@ urlpatterns = [
 
     # Scripts
     path('scripts/', views.ScriptListView.as_view(), name='script_list'),
-    path('scripts/<str:module>.<str:name>/', views.ScriptView.as_view(), name='script'),
     path('scripts/results/<int:job_result_pk>/', views.ScriptResultView.as_view(), name='script_result'),
+    re_path(r'^scripts/(?P<module>.([^.]+)).(?P<name>.(.+))/', views.ScriptView.as_view(), name='script'),
 
 ]

+ 1 - 1
netbox/templates/extras/script_list.html

@@ -34,7 +34,7 @@
                 {% for class_name, script in module_scripts.items %}
                   <tr>
                     <td>
-                      <a href="{% url 'extras:script' module=script.module name=class_name %}" name="script.{{ class_name }}">{{ script.name }}</a>
+                      <a href="{% url 'extras:script' module=script.root_module name=class_name %}" name="script.{{ class_name }}">{{ script.name }}</a>
                     </td>
                     <td>
                       {% include 'extras/inc/job_label.html' with result=script.result %}