jobs.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from dataclasses import dataclass
  2. from typing import List
  3. from netbox.jobs import AsyncViewJob
  4. from utilities.request import copy_safe_request
  5. __all__ = (
  6. 'AsyncJobData',
  7. 'is_background_request',
  8. 'process_request_as_job',
  9. )
  10. @dataclass
  11. class AsyncJobData:
  12. log: List[str]
  13. errors: List[str]
  14. def is_background_request(request):
  15. """
  16. Return True if the request is being processed as a background job.
  17. """
  18. return getattr(request, '_background', False)
  19. def process_request_as_job(view, request, name=None):
  20. """
  21. Process a request using a view as a background job.
  22. """
  23. # Check that the request that is not already being processed as a background job (would be a loop)
  24. if is_background_request(request):
  25. return
  26. # Create a serializable copy of the original request
  27. request_copy = copy_safe_request(request)
  28. request_copy._background = True
  29. # Enqueue a job to perform the work in the background
  30. return AsyncViewJob.enqueue(
  31. name=name,
  32. user=request.user,
  33. view_cls=view,
  34. request=request_copy,
  35. )