-
Notifications
You must be signed in to change notification settings - Fork 10
feat: allow for task service calls from django admin UI #362
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
joseph-sentry
wants to merge
1
commit into
main
Choose a base branch
from
joseph/django-admin-ui
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| import inspect | ||
| import json | ||
|
|
||
| from django import forms | ||
| from django.core.exceptions import ValidationError | ||
|
|
||
| from services.task.task import TaskService | ||
|
|
||
| task_service = TaskService() | ||
|
|
||
|
|
||
| class TaskServiceSubmissionForm(forms.Form): | ||
| def _get_task_info(self): | ||
| task_choices = [("", "-- Select a task method --")] | ||
| task_info = {} | ||
|
|
||
| for method_name in dir(task_service): | ||
| if method_name.startswith("_"): | ||
| continue | ||
| if method_name in ["schedule_task"]: | ||
| continue | ||
| if method_name.endswith("_signature"): | ||
| continue | ||
|
|
||
| method = getattr(task_service, method_name) | ||
| if not callable(method): | ||
| continue | ||
|
|
||
| try: | ||
| sig = inspect.signature(method) | ||
| parameters = [] | ||
| required_params = [] | ||
| optional_params = [] | ||
|
|
||
| for name, param in sig.parameters.items(): | ||
| if name == "self": | ||
| continue | ||
|
|
||
| param_info = { | ||
| "name": name, | ||
| "type": str(param.annotation) | ||
| if param.annotation != param.empty | ||
| else "Any", | ||
| "default": str(param.default) | ||
| if param.default != param.empty | ||
| else None, | ||
| "required": param.default == param.empty, | ||
| } | ||
|
|
||
| parameters.append(param_info) | ||
|
|
||
| if param.default == param.empty: | ||
| required_params.append(name) | ||
| else: | ||
| optional_params.append(name) | ||
|
|
||
| task_info[method_name] = { | ||
| "description": f"TaskService.{method_name}", | ||
| "signature": str(sig), | ||
| "parameters": parameters, | ||
| "required": required_params, | ||
| "optional": optional_params, | ||
| } | ||
| except Exception: | ||
| continue | ||
|
|
||
| task_choices.extend( | ||
| [(method_name, method_name) for method_name in sorted(task_info.keys())] | ||
| ) | ||
|
|
||
| return {"choices": task_choices, "info": task_info} | ||
|
|
||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| task_info = self._get_task_info() | ||
|
|
||
| self.fields["task_method"] = forms.ChoiceField( | ||
| label="Select Task Method", | ||
| help_text="Choose a TaskService method to execute", | ||
| required=True, | ||
| choices=task_info["choices"], | ||
| widget=forms.Select( | ||
| attrs={ | ||
| "class": "vTextField", | ||
| "style": "width: 100%;", | ||
| "onchange": "updateTaskPreview(this.value)", | ||
| } | ||
| ), | ||
| ) | ||
|
|
||
| self.fields["task_preview"] = forms.CharField( | ||
| label="Method Signature & Parameters", | ||
| help_text="Function signature and parameters for the selected method", | ||
| required=False, | ||
| widget=forms.Textarea( | ||
| attrs={ | ||
| "class": "vLargeTextField", | ||
| "rows": 8, | ||
| "cols": 80, | ||
| "readonly": "readonly", | ||
| "style": "width: 100%; font-family: monospace; background-color: #1e1e1e; color: #d4d4d4; border: 1px solid #3c3c3c;", | ||
| "id": "task-preview-field", | ||
| } | ||
| ), | ||
| initial="Select a task method to see its signature and parameters", | ||
| ) | ||
|
|
||
| self.fields["method_kwargs"] = forms.CharField( | ||
| label="Method Arguments", | ||
| help_text="JSON object with method keyword arguments (e.g., {'repoid': 1, 'commitid': 'abc123'})", | ||
| widget=forms.Textarea( | ||
| attrs={ | ||
| "class": "vLargeTextField", | ||
| "rows": 12, | ||
| "cols": 80, | ||
| "placeholder": '{\n "repoid": 1,\n "commitid": "abc123"\n}', | ||
| "style": "width: 100%; font-family: monospace;", | ||
| } | ||
| ), | ||
| initial="{}", | ||
| ) | ||
|
|
||
| def clean(self): | ||
| cleaned_data = super().clean() | ||
| if not cleaned_data: | ||
| return cleaned_data | ||
| task_method = cleaned_data.get("task_method") | ||
|
|
||
| if not task_method: | ||
| raise ValidationError("Please select a task method.") | ||
|
|
||
| return cleaned_data | ||
|
|
||
| def clean_method_kwargs(self): | ||
| if not self.cleaned_data: | ||
| return {} | ||
| method_kwargs = self.cleaned_data.get("method_kwargs", "{}") | ||
| try: | ||
| parsed = json.loads(method_kwargs) | ||
| if not isinstance(parsed, dict): | ||
| raise ValidationError( | ||
| "Method arguments must be a JSON object (dictionary)." | ||
| ) | ||
| return parsed | ||
| except json.JSONDecodeError as e: | ||
| raise ValidationError(f"Invalid JSON format: {e}") | ||
|
|
||
| def get_task_parameter_info_json(self): | ||
| return json.dumps(self._get_task_info()["info"]) | ||
|
|
||
| def call_task_method(self): | ||
| task_method = self.cleaned_data.get("task_method") | ||
| method_kwargs = self.cleaned_data.get("method_kwargs", {}) | ||
|
|
||
| if not task_method: | ||
| raise ValidationError("No task method selected") | ||
|
|
||
| try: | ||
| method = getattr(task_service, task_method) | ||
|
|
||
| if not callable(method): | ||
| raise ValidationError(f"Method '{task_method}' is not callable") | ||
|
|
||
| result = method(**method_kwargs) | ||
| return result | ||
|
|
||
| except ImportError: | ||
| raise ValidationError("Cannot import TaskService") | ||
| except AttributeError: | ||
| raise ValidationError(f"Method '{task_method}' not found on TaskService") | ||
| except TypeError as e: | ||
| raise ValidationError( | ||
| f"Invalid arguments for method '{task_method}': {str(e)}" | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential bug: Undefined variables `task_method`, `method_kwargs` in `except` block cause `NameError` and admin crash.
submit_task_viewfunction attempts to logtask_methodandmethod_kwargswithin itsexceptblock. Ifform.call_task_method()on line 170 raises an exception (e.g., a Celery broker connection error or serialization error not caught bycall_task_method's internalexceptblock), thentask_methodandmethod_kwargs(assigned on lines 171-172) will not have been defined. This leads to aNameErrorduring logging, masking the original issue and causing the admin interface to crash, hindering debugging.task_methodandmethod_kwargsare defined beforeform.call_task_method()or access them directly fromform.cleaned_datawithin theexceptblock.severity: 0.95, confidence: 0.98
Did we get this right? 👍 / 👎 to inform future reviews.