nautobot.apps.jobs - Nautobot Documentation

Skip to content

# `nautobot.apps.jobs`

Nautobot Jobs API.

## `nautobot.apps.jobs.BaseJob`

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)
- approval_required (bool)
- dryrun_default (bool)
- field_order (list)
- has_sensitive_variables (bool)
- hidden (bool)
- soft_time_limit (int)
- task_queues (list)
- template_name (str)
- time_limit (int)
- is_singleton (bool)

### `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.

### `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
--- | ---
`Any` | The return value of this handler is ignored normally, except if `self.fail()` is called herein, in which case the return value will be used as the overall JobResult return value since `self.run()` will not be called in such a case.

### `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.

### `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`.

### `fail(msg, *args, **kwargs)`

Mark this job as failed without immediately raising an exception and aborting.

### `file_path()`

Deprecated as of Nautobot 2.2.3.

### `load_json(filename)`

Return data from a JSON file

### `load_yaml(filename)`

Return data from a YAML file

### `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` | `Any` | Exception raised by the task (if any) or return value from the task, if it failed cleanly, such as if the Job called `self.fail()` rather than raising an exception. | 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, or None. | 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.

### `registered_name()`

Deprecated - use class_path classproperty instead.

### `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.

### `singleton_cache_key()`

Cache key for singleton jobs.

## `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, may_reload_jobs=True, jobhook_queryset=None)`

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

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`object_change` | `ObjectChange` | The change that may trigger JobHooks to execute. | required
`may_reload_jobs` | `bool` | Whether to reload JobHook source code from disk to guarantee up-to-date code. | `True`
`jobhook_queryset` | `QuerySet` | Previously retrieved set of JobHooks to potentially enqueue | `None`

Returns:

Name | Type | Description
--- | --- | ---
`result` | `tuple[bool, QuerySet]` | whether Jobs were reloaded here, and the jobhooks that were considered

## `nautobot.apps.jobs.get_job(class_path, reload=False)`

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

May return None if the job can't be imported.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`reload` | `bool` | If True, and the given class_path describes a JOBS_ROOT or GitRepository Job, then refresh all such Jobs before retrieving the job class. | `False`

## `nautobot.apps.jobs.get_jobs(*, reload=False)`

Compile a dictionary of all Job classes available at this time.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`reload` | `bool` | If True, reimport Jobs from `JOBS_ROOT` and all applicable GitRepositories. | `False`

Returns:

Type | Description
--- | ---
`dict` | `{"class_path.Job1": <job_class>, "class_path.Job2": <job_class>, ...}`

## `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)`

Method to register jobs - with Celery in Nautobot 2.0 through 2.2.2, with Nautobot itself in 2.2.3 and later.