Skip to content

nautobot.apps.jobs

Nautobot Jobs API.

nautobot.apps.jobs.BaseJob

Bases: Task

Base model for jobs.

Users can subclass this directly if they want to provide their own base class for implementing multiple jobs with shared functionality; if no such sharing is required, use Job class instead.

Jobs must define at minimum a run method.

Meta

Metaclass attributes - subclasses can define any or all of the following attributes:

  • name (str)
  • description (str)
  • hidden (bool)
  • field_order (list)
  • approval_required (bool)
  • soft_time_limit (int)
  • time_limit (int)
  • has_sensitive_variables (bool)
  • task_queues (list)

after_return(status, retval, task_id, args, kwargs, einfo)

Handler called after the task returns.

Parameters:

Name Type Description Default
status str

Current task state.

required
retval Any

Task return value/exception.

required
task_id str

Unique id of the task.

required
args tuple

Original arguments for the task that returned.

required
kwargs dict

Original keyword arguments for the task that returned.

required
einfo ExceptionInfo

ExceptionInfo instance, containing the traceback (if any).

required

Returns:

Type Description
None

The return value of this handler is ignored.

apply(args=None, kwargs=None, link=None, link_error=None, task_id=None, retries=None, throw=None, logfile=None, loglevel=None, headers=None, **options)

Fix celery's apply method to propagate options to the task result

as_form(data=None, files=None, initial=None, approval_view=False) classmethod

Return a Django form suitable for populating the context data required to run this Job.

approval_view will disable all fields from modification and is used to display the form during a approval review workflow.

as_form_class() classmethod

Dynamically generate a Django form class corresponding to the variables in this Job.

In most cases you should use .as_form() instead of calling this method directly.

before_start(task_id, args, kwargs)

Handler called before the task starts.

Parameters:

Name Type Description Default
task_id str

Unique id of the task to execute.

required
args Tuple

Original arguments for the task to execute.

required
kwargs Dict

Original keyword arguments for the task to execute.

required

Returns:

Type Description
None

The return value of this handler is ignored.

class_path()

Unique identifier of a specific Job class, in the form ..

Examples: - my_script.MyScript - Local Job - nautobot.core.jobs.MySystemJob - System Job - my_plugin.jobs.MyPluginJob - App-provided Job - git_repository.jobs.myjob.MyJob - GitRepository Job

class_path_dotted()

Dotted class_path, suitable for use in things like Python logger names.

Deprecated as of Nautobot 2.0: just use .class_path instead.

class_path_js_escaped()

Escape various characters so that the class_path can be used as a jQuery selector.

clear_cache()

Clear all cached properties on this instance without accessing them. This is required because celery reuses task instances for multiple runs.

create_file(filename, content)

Create a file that can later be downloaded by users.

Parameters:

Name Type Description Default
filename str

Name of the file to create, including extension

required
content (str, bytes)

Content to populate the created file with.

required

Raises:

Type Description
ValueError

if the provided content exceeds JOB_CREATE_FILE_MAX_SIZE in length

Returns:

Type Description
FileProxy

record that was created

deserialize_data(data) classmethod

Given data input for a job execution, deserialize it by resolving object references using defined variables.

This converts a list of pk's back into a QuerySet for MultiObjectVar instances and single pk values into model instances for ObjectVar.

Note that when resolving querysets or model instances by their PK, we do not catch DoesNotExist exceptions here, we leave it up the caller to handle those cases. The normal job execution code path would consider this a failure of the job execution, as described in nautobot.extras.jobs.run_job.

load_json(filename)

Return data from a JSON file

load_yaml(filename)

Return data from a YAML file

on_bound(app) classmethod

Called when the task is bound to an app.

Note

This class method can be defined to do additional actions when the task class is bound to an app.

on_failure(exc, task_id, args, kwargs, einfo)

Error handler.

This is run by the worker when the task fails.

Parameters:

Name Type Description Default
exc Exception

The exception raised by the task.

required
task_id str

Unique id of the failed task.

required
args Tuple

Original arguments for the task that failed.

required
kwargs Dict

Original keyword arguments for the task that failed.

required
einfo ~ExceptionInfo

Exception information.

required

Returns:

Type Description
None

The return value of this handler is ignored.

on_retry(exc, task_id, args, kwargs, einfo)

Retry handler.

This is run by the worker when the task is to be retried.

Parameters:

Name Type Description Default
exc Exception

The exception sent to :meth:retry.

required
task_id str

Unique id of the retried task.

required
args Tuple

Original arguments for the retried task.

required
kwargs Dict

Original keyword arguments for the retried task.

required
einfo ~ExceptionInfo

Exception information.

required

Returns:

Type Description
None

The return value of this handler is ignored.

on_success(retval, task_id, args, kwargs)

Success handler.

Run by the worker if the task executes successfully.

Parameters:

Name Type Description Default
retval Any

The return value of the task.

required
task_id str

Unique id of the executed task.

required
args Tuple

Original arguments for the executed task.

required
kwargs Dict

Original keyword arguments for the executed task.

required

Returns:

Type Description
None

The return value of this handler is ignored.

prepare_job_kwargs(job_kwargs) classmethod

Process dict and return kwargs that exist as ScriptVariables on this job.

properties_dict()

Return all relevant classproperties as a dict.

Used for convenient rendering into job_edit.html via the json_script template tag.

run(*args, **kwargs)

Method invoked when this Job is run.

serialize_data(data) staticmethod

This method parses input data (from JobForm usually) and returns a dict which is safe to serialize

Here we convert the QuerySet of a MultiObjectVar to a list of the pk's and the model instance of an ObjectVar into the pk value.

These are converted back during job execution.

shadow_name(args, kwargs, options)

Override for custom task name in worker logs/monitoring.

Example

from celery.utils.imports import qualname

def shadow_name(task, args, kwargs, options): return qualname(args[0])

@app.task(shadow_name=shadow_name, serializer='pickle') def apply_function_async(fun, args, kwargs): return fun(args, **kwargs)

Parameters:

Name Type Description Default
args Tuple

Task positional arguments.

required
kwargs Dict

Task keyword arguments.

required
options Dict

Task execution options.

required

nautobot.apps.jobs.BooleanVar

Bases: ScriptVariable

Boolean representation (true/false). Renders as a checkbox.

nautobot.apps.jobs.ChoiceVar

Bases: ScriptVariable

Select one of several predefined static choices, passed as a list of two-tuples. Example:

color = ChoiceVar(
    choices=(
        ('#ff0000', 'Red'),
        ('#00ff00', 'Green'),
        ('#0000ff', 'Blue')
    )
)

nautobot.apps.jobs.DatabaseFileField

Bases: FileField

Specialized FileField for use with DatabaseFileStorage storage backend.

nautobot.apps.jobs.DryRunVar

Bases: BooleanVar

Special boolean variable that bypasses approval requirements if this is set to True on job execution.

nautobot.apps.jobs.FileVar

Bases: ScriptVariable

An uploaded file.

nautobot.apps.jobs.GitRepositoryDryRun

Bases: Job

System Job to perform a dry run on a Git repository.

nautobot.apps.jobs.GitRepositorySync

Bases: Job

System job to clone and/or pull a Git repository, then invoke refresh_datasource_content().

nautobot.apps.jobs.IPAddressVar

Bases: ScriptVariable

An IPv4 or IPv6 address without a mask.

nautobot.apps.jobs.IPAddressWithMaskVar

Bases: ScriptVariable

An IPv4 or IPv6 address with a mask.

nautobot.apps.jobs.IPNetworkVar

Bases: ScriptVariable

An IPv4 or IPv6 prefix.

nautobot.apps.jobs.IntegerVar

Bases: ScriptVariable

Integer representation. Can enforce minimum/maximum values.

nautobot.apps.jobs.JSONVar

Bases: ScriptVariable

Like TextVar but with native serializing of JSON data.

nautobot.apps.jobs.Job

Bases: BaseJob

Classes which inherit from this model will appear in the list of available jobs.

nautobot.apps.jobs.JobButtonReceiver

Bases: Job

Base class for job button receivers. Job button receivers are jobs that are initiated from UI buttons and are not intended to be run from the job form UI or API like standard jobs.

receive_job_button(obj)

Method to be implemented by concrete JobButtonReceiver subclasses.

Parameters:

Name Type Description Default
obj Model

an instance of the object that triggered this job

required

run(object_pk, object_model_name)

JobButtonReceiver subclasses generally shouldn't need to override this method.

nautobot.apps.jobs.JobHookReceiver

Bases: Job

Base class for job hook receivers. Job hook receivers are jobs that are initiated from object changes and are not intended to be run from the UI or API like standard jobs.

receive_job_hook(change, action, changed_object)

Method to be implemented by concrete JobHookReceiver subclasses.

Parameters:

Name Type Description Default
change ObjectChange

an instance of nautobot.extras.models.ObjectChange

required
action str

a string with the action performed on the changed object ("create", "update" or "delete")

required
changed_object Model

an instance of the object that was changed, or None if the object has been deleted

required

run(object_change)

JobHookReceiver subclasses generally shouldn't need to override this method.

nautobot.apps.jobs.MultiChoiceVar

Bases: ChoiceVar

Like ChoiceVar, but allows for the selection of multiple choices.

nautobot.apps.jobs.MultiObjectVar

Bases: ObjectVar

Like ObjectVar, but can represent one or more objects.

nautobot.apps.jobs.NautobotKombuJSONEncoder

Bases: JSONEncoder

Custom json encoder based on restframework's JSONEncoder that serializes objects that implement the nautobot_serialize() method via the __nautobot_type__ interface. This is useful in passing special objects to and from Celery tasks.

This pattern should generally be avoided by passing pointers to persisted objects to the Celery tasks and retrieving them from within the task execution. While this is always possible for model instances (which covers 99% of use cases), for rare instances where it does not, and the actual object must be passed, this pattern allows for encoding and decoding of such objects.

It requires a conforming class to implement the instance method nautobot_serialize() which returns a json serializable dictionary of the object representation. The class must also implement the nautobot_deserialize() class method which takes the dictionary representation and returns an actual instance of the class.

nautobot.apps.jobs.ObjectVar

Bases: ScriptVariable

A single object within Nautobot.

Parameters:

Name Type Description Default
model Model

The Nautobot model being referenced

None
display_field str

The attribute of the returned object to display in the selection list

'display'
query_params dict

Additional query parameters to attach when making REST API requests

None
null_option str

The label to use as a "null" selection option

None

nautobot.apps.jobs.RunJobTaskFailed

Bases: Exception

Celery task failed for some reason.

nautobot.apps.jobs.ScriptVariable

Base model for script variables

as_field()

Render the variable as a Django form field.

nautobot.apps.jobs.StringVar

Bases: ScriptVariable

Character string representation. Can enforce minimum/maximum length and/or regex validation.

nautobot.apps.jobs.TextVar

Bases: ScriptVariable

Free-form text data. Renders as a <textarea>.

nautobot.apps.jobs.enqueue_job_hooks(object_change)

Find job hook(s) assigned to this changed object type + action and enqueue them to be processed

nautobot.apps.jobs.get_job(class_path)

Retrieve a specific job class by its class_path (<module_name>.<JobClassName>).

May return None if the job isn't properly registered with Celery at this time.

nautobot.apps.jobs.is_job(obj)

Returns True if the given object is a Job subclass.

nautobot.apps.jobs.is_variable(obj)

Returns True if the object is a ScriptVariable instance.

nautobot.apps.jobs.register_jobs(*jobs)

Helper method to register jobs with Celery