Python API

Database Primitives

Models

class nsot.models.Assignment(*args, **kwargs)[source]

DB object for assignment of addresses to interfaces (on devices).

This is used to enforce constraints at the relationship level for addition of new address assignments.

exception DoesNotExist
exception MultipleObjectsReturned
clean_address(value)[source]

Enforce that new addresses can only be host addresses.

clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

class nsot.models.Attribute(*args, **kwargs)[source]

Represents a flexible attribute for Resource objects.

exception DoesNotExist
exception MultipleObjectsReturned
clean_constraints(value)[source]

Enforce formatting of constraints.

clean_default(value)[source]

Validate the default value against multi type and constraints.

clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

clean_inheritable(value)[source]

Validate that inheritable is only set for hierarchical resources.

property default

Get the default value, unwrapping from internal storage format.

delete(*args, **kwargs)[source]

Prevent deletion if other attributes depend on this one.

get_all_dependencies()[source]

Return the full set of transitive dependencies (not just direct).

save(*args, **kwargs)[source]

Always enforce constraints.

validate_dependencies()[source]

Validate that depends_on entries are valid (same site/resource_name, no cycles).

class nsot.models.Change(*args, **kwargs)[source]

Record of all changes in NSoT.

exception DoesNotExist
exception MultipleObjectsReturned
clean_fields(exclude=None)[source]

This will populate the change fields from the incoming object.

clean_site(obj)[source]

value in this case is an instance of a model object.

property diff

Return a text diff between previous and current resource state.

property resource_diff

Return a dict of changed fields with old/new values.

save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

class nsot.models.Circuit(*args, **kwargs)[source]

Represents two network Interfaces that are connected

exception DoesNotExist
exception MultipleObjectsReturned
property addresses

Return addresses associated with this circuit.

This includes addresses associated with all descendant interfaces.

clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

property devices

Return devices associated with this circuit.

interface_for(device)[source]

Given a Device object, return the interface attached to this Circuit which belongs to that Device. If both ends of the Circuit are attached to the Device, the A-side is returned.

If neither ends of this Circuit are attached to Device, then None is returned

property interfaces

Return interfaces associated with this circuit.

class nsot.models.Device(*args, **kwargs)[source]

Represents a network device.

exception DoesNotExist
exception MultipleObjectsReturned
property circuits

All circuits related to this Device.

clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

class nsot.models.Interface(*args, **kwargs)[source]

A network interface.

exception DoesNotExist
exception MultipleObjectsReturned
assign_address(cidr)[source]

Assign an address to this interface.

Must have prefix of /32 (IPv4) or /128 (IPv6).

Parameters:

cidr – IPv4/v6 CIDR host address or Network object

property circuit

Return the Circuit I am associated with

clean_addresses()[source]

Make sure that addresses/networks are saved as JSON.

clean_device_hostname(device)[source]

Extract hostname from device

clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

clean_mac_address(value)[source]

Enforce valid mac_address.

clean_mtu(value)[source]

Enforce valid MTU.

clean_name(value)[source]

Enforce name.

clean_name_slug(value=None)[source]

Slugify the interface name into natural key.

clean_speed(value)[source]

Enforce valid speed.

clean_type(value)[source]

Enforce valid type. Accepts integer IDs or string names.

get_addresses()[source]

Return a list of assigned addresses.

get_ancestors()[source]

Return all ancestors of an Interface.

get_assignments()[source]

Return a list of information about my assigned addresses.

get_children()[source]

Return the immediate children of an Interface.

get_descendants()[source]

Return all the descendants of an Interface.

get_mac_address()[source]

Return a serializable representation of mac_address.

get_networks()[source]

Return a list of attached Networks.

get_root()[source]

Return the parent of all ancestors of an Interface.

get_siblings()[source]

Return Interfaces with the same parent and device id as an Interface.

property networks

Return all the parent Networks for my addresses.

save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

set_addresses(addresses, overwrite=False, partial=False)[source]

Explicitly assign a list of addresses to this Interface.

Parameters:
  • addresses – A list of CIDRs

  • overwrite – Whether to purge existing assignments before assigning.

  • partial – Whether this is a partial update.

class nsot.models.Network(*args, **kwargs)[source]

Represents a subnet or IP address.

exception DoesNotExist
exception MultipleObjectsReturned
clean_fields(exclude=None)[source]

This will enforce correct values on fields.

clean_state(value)[source]

Enforce that state is one of the valid states.

get_ancestors(ascending=False)[source]

Return my ancestors.

get_children()[source]

Return my immediate children.

get_descendants()[source]

Return all of my children!

get_next_address(num=1, strict=False, as_objects=True)[source]

Return a list of the next available addresses.

If no addresses are available, an empty list will be returned.

Parameters:
  • num – The number of addresses desired

  • as_objects – Whether to return IPNetwork objects or strings

get_next_network(prefix_length, num=1, strict=False, as_objects=True)[source]

Return a list of the next available networks.

If no networks are available, an empty list will be returned.

Parameters:
  • prefix_length – The prefix length of networks

  • num – The number of networks desired

  • as_objects – Whether to return IPNetwork objects or strings

  • strict – Whether to return networks for strict allocation

Returns:

list(IPNetwork)

get_root()[source]

Returns the root node (the parent of all of my ancestors).

get_siblings(include_self=False)[source]

Return my siblings. Root nodes are siblings to other root nodes.

is_child_node()[source]

Returns whether I am a child node.

is_leaf_node()[source]

Returns whether I am leaf node (no children).

is_root_node()[source]

Returns whether I am a root node (no parent).

reparent_subnets()[source]

Determine list of child nodes and set the parent to self.

save(*args, **kwargs)[source]

This is stuff we want to happen upon save.

class nsot.models.Protocol(*args, **kwargs)[source]

Representation of a routing protocol

exception DoesNotExist
exception MultipleObjectsReturned
clean_circuit(value)[source]

Ensure at least one endpoint on the circuit is on this device

clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

clean_interface(value)[source]

Ensure that the interface is bound to the same device this Protocol is bound to.

clean_type(value)[source]

Ensure that ProtocolType matches our site.

set_attributes(attributes, valid_attributes=None, partial=False)[source]

Ensure that all attributes are set that are required by the set ProtocolType.

class nsot.models.ProtocolType(*args, **kwargs)[source]

Representation of protocol types (e.g. bgp, is-is, ospf, etc.)

exception DoesNotExist
exception MultipleObjectsReturned
get_required_attributes()[source]

Return a list of the names of self.required_attributes.

class nsot.models.Site(*args, **kwargs)[source]

A namespace for attribtues, devices, and networks.

exception DoesNotExist
exception MultipleObjectsReturned
clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

class nsot.models.User(*args, **kwargs)[source]

A custom user object that utilizes email as the username.

Replaces the former custom_user.models.AbstractEmailUser base class with an equivalent inline implementation based on AbstractBaseUser and PermissionsMixin.

The following attributes are inherited from the superclasses:
  • password

  • last_login

  • is_superuser

exception DoesNotExist
exception MultipleObjectsReturned
clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

email_user(subject, message, from_email=None, **kwargs)[source]

Send an email to this User.

generate_auth_token()[source]

Serialize user data and encrypt token.

get_full_name()[source]

Return the email.

get_short_name()[source]

Return the email.

save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

classmethod verify_auth_token(email, auth_token, expiration=None)[source]

Verify token and return a User object.

verify_secret_key(secret_key)[source]

Validate secret_key

class nsot.models.Value(*args, **kwargs)[source]

Represents a value for an attribute attached to a Resource.

exception DoesNotExist
exception MultipleObjectsReturned
clean_fields(exclude=None)[source]

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

clean_site(value)[source]

Always enforce that site is set.

save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

Fields

class nsot.fields.BinaryIPAddressField(*args, **kwargs)[source]

IP Address field that stores values as varbinary.

db_type(connection)[source]

Return the database column data type for this field, for the provided connection.

from_db_value(value, expression, connection)[source]

DB -> Python.

get_db_prep_value(value, connection, prepared=False)[source]

Python -> DB.

to_python(value)[source]

Object -> Python.

class nsot.fields.JSONField(*args, **kwargs)[source]

JSONField is a generic textfield that neatly serializes/unserializes JSON objects seamlessly. Main thingy must be a dict object.

deconstruct()[source]

Return enough information to recreate the field as a 4-tuple:

  • The name of the field on the model, if contribute_to_class() has been run.

  • The import path of the field, including the class, e.g. django.db.models.IntegerField. This should be the most portable version, so less specific may be better.

  • A list of positional arguments.

  • A dict of keyword arguments.

Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types):

  • None, bool, str, int, float, complex, set, frozenset, list, tuple, dict

  • UUID

  • datetime.datetime (naive), datetime.date

  • top-level classes, top-level functions - will be referenced by their full import path

  • Storage instances - these have their own deconstruct() method

This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined.

There’s no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values.

get_db_prep_save(value, connection, **kwargs)[source]

Convert our JSON object to a string before we save

get_default()[source]

Return the default value for this field.

get_prep_value(value)[source]

Perform preliminary non-db specific value checks and conversions.

to_python(value)[source]

Convert our string value to JSON after we load it from the DB

class nsot.fields.MACAddressField(*args, **kwargs)[source]

Subclass of base field to raise a DRF ValidationError.

DRF handles Django’s default ValidationError, but this is so that we can always expect the DRF version, for better consistency in debugging and testing.

to_python(value)[source]

Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can’t be converted. Return the converted value. Subclasses should override this.

Validators

Validators for validating object fields.

nsot.validators.validate_cidr(value)[source]

Validate whether value is a validr IPv4/IPv6 CIDR.

nsot.validators.validate_email(value)[source]

Validate whether value is an email address.

nsot.validators.validate_host_address(value)[source]

Validate whether value is a host IP address.

nsot.validators.validate_mac_address(value)[source]

Validate whether value is a valid MAC address.

nsot.validators.validate_name(value)[source]

Validate whether value is a valid name.

Exceptions

exception nsot.exc.BadRequest(detail=None, code=None)[source]

HTTP 400 error.

exception nsot.exc.BaseHttpError(detail=None, code=None)[source]

Base HTTP error.

exception nsot.exc.Conflict(detail=None, code=None)[source]

HTTP 409 error.

nsot.exc.DjangoValidationError

alias of ValidationError

exception nsot.exc.Error(detail=None, code=None)[source]

Baseclass for NSoT Exceptions.

exception nsot.exc.Forbidden(detail=None, code=None)[source]

HTTP 403 error.

exception nsot.exc.ModelError(detail=None, code=None)[source]

Base class for NSoT Model Exceptions.

exception nsot.exc.MultipleObjectsReturned[source]

The query returned multiple objects when only one was expected.

exception nsot.exc.NotFound(detail=None, code=None)[source]

HTTP 404 error.

exception nsot.exc.ObjectDoesNotExist[source]

The requested object does not exist

exception nsot.exc.ProtectedError(msg, protected_objects)[source]
exception nsot.exc.Unauthorized(detail=None, code=None)[source]

HTTP 401 error.

exception nsot.exc.ValidationError(detail=None, code=None)[source]

REST API Primitives

Views

class nsot.api.views.AttributeViewSet(**kwargs)[source]

API endpoint that allows Attributes to be viewed or edited.

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

serializer_class

alias of AttributeSerializer

class nsot.api.views.AuthTokenLoginView(**kwargs)[source]
class nsot.api.views.AuthTokenVerifyView(**kwargs)[source]
class nsot.api.views.BaseNsotViewSet(**kwargs)[source]

Default viewset for Nsot objects with the following defaults:

  • Objects are designed to be nested under site resources, but can also be top-level resources.

get_natural_key_kwargs(filter_value)[source]

This method should take value and return a dictionary containing the natural key fields used to filter results.

This is called internally by self.get_object() if a subclass has defined a natural_key.

Parameters:

filter_value – Value to be used to filter by natural_key

get_object()[source]

Enhanced default to support looking up objects for:

  • Natural key lookups for resource objects (e.g. Device.hostname)

  • Inject of site into filter lookup if site_pk is set.

Currently this does NOT filter the queryset, which should not be a problem as we were never using .get_object() before. See the FIXME comments for more context.

list(request, site_pk=None, queryset=None, serializer_class=None, *args, **kwargs)[source]

List objects optionally filtered by site.

Parameters:

serializer_class – Optional serializer class override for cross-model detail routes (e.g. CircuitViewSet.interfaces() passing InterfaceSerializer).

natural_key = None

Natural key for the resource. If not defined, defaults to pk-only.

not_found(pk=None, site_pk=None, msg=None)[source]

Standard formatting for 404 errors.

retrieve(request, pk=None, site_pk=None, *args, **kwargs)[source]

Retrieve a single object optionally filtered by site.

success(data, status=None, headers=None)[source]

Return a positive API response.

Parameters:
  • data – Serialized data

  • status – (Optional) HTTP status code

  • headers – (Optional) Dict of extra headers

class nsot.api.views.ChangeViewSet(**kwargs)[source]

Read-only API endpoint that allows Changes to be viewed.

All Create/Update/Delete events are logged as a Change. A Change includes information such as the change time, user, and the full resource after modification. Changes are immutable and can only be removed by deleting the entire Site.

filterset_class

alias of ChangeFilter

serializer_class

alias of ChangeSerializer

class nsot.api.views.CircuitViewSet(**kwargs)[source]

API endpoint that allows Circuits to be viewed or edited.

addresses(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return a list of addresses for the interfaces on this Circuit.

bulk_update(request, *args, **kwargs)[source]

Workaround for bulk update of objects with unique constraint.

At this time this is only required by the Circuit object, which is why it is only defined here.

Credit: https://github.com/miki725/django-rest-framework-bulk/issues/30 Source: http://bit.ly/2HcyNnG

devices(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return a list of devices for this Circuit.

filterset_class

alias of CircuitFilter

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

interfaces(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return a list of interfaces for this Circuit.

natural_key = 'name_slug'

Natural key for the resource. If not defined, defaults to pk-only.

serializer_class

alias of CircuitSerializer

class nsot.api.views.DeviceViewSet(**kwargs)[source]

API endpoint that allows Devices to be viewed or edited.

circuits(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return a list of Circuits for this Device

filterset_class

alias of DeviceFilter

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

interfaces(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return all interfaces for this Device.

natural_key = 'hostname'

Natural key for the resource. If not defined, defaults to pk-only.

serializer_class

alias of DeviceSerializer

class nsot.api.views.InterfaceViewSet(**kwargs)[source]

API endpoint that allows Interfaces to be viewed or edited.

addresses(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return a list of addresses for this Interface.

ancestors(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return all the ancestors of this Interface.

assignments(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return a list of information about my assigned addresses.

children(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return all the immediate children of this Interface.

circuit(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the Circuit I am associated with

descendants(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return all the descendants of this Interface.

filterset_class

alias of InterfaceFilter

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

natural_key = 'name_slug'

Natural key for the resource. If not defined, defaults to pk-only.

networks(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return all the containing Networks for my assigned addresses.

parent(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the parent of this Interface.

root(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the root of the tree this Interface is part of.

serializer_class

alias of InterfaceSerializer

siblings(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return all the siblings of this Interface.

class nsot.api.views.NetworkViewSet(**kwargs)[source]

API endpoint that allows Networks to be viewed or edited.

ancestors(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return ancestors of this Network.

assignments(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the interface assignments for this Network.

children(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the immediate children of this Network.

closest_parent(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the closest matching parent of this Network even if it doesn’t exist in the database.

descendants(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return descendants of this Network.

filterset_class

alias of NetworkFilter

get_natural_key_kwargs(filter_value)[source]

Return a dict of kwargs for natural_key lookup.

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

natural_key = 'cidr'

Natural key for the resource. If not defined, defaults to pk-only.

next_address(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return next available IPs from this Network.

next_network(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return next available networks from this Network.

parent(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the parent of this Network.

perform_destroy(instance)[source]

Overload default to handle non-serializer exceptions, and log Change events. :param instance:

Model instance to delete

query(request, site_pk=None, *args, **kwargs)[source]

Override base query to inherit filtering by query params.

reserved(request, site_pk=None, *args, **kwargs)[source]

Display all reserved Networks.

root(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return the parent of all ancestors for this Network.

serializer_class

alias of NetworkSerializer

siblings(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return Networks with the same parent. Root nodes are siblings to other root nodes.

subnets(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return subnets of this Network.

supernets(request, pk=None, site_pk=None, *args, **kwargs)[source]

Return supernets of this Network.

class nsot.api.views.NotFoundViewSet(**kwargs)[source]

Catchall for bad API endpoints.

get_queryset()[source]

Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using self.queryset.

This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests.

You may want to override this if you need to provide different querysets depending on the incoming request.

(Eg. return a list of items that is specific to the user)

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

class nsot.api.views.NsotBulkUpdateModelMixin[source]

The default mixin isn’t using super() so multiple-inheritance breaks. This fixes it for our use-case.

class nsot.api.views.NsotViewSet(**kwargs)[source]

Generic mutable viewset that logs all change events and includes support for bulk creation of objects.

bulk_destroy(request, site_pk=None, *args, **kwargs)[source]

Delete multiple objects by providing a list of IDs in the request body.

Accepts a JSON list of integer IDs, e.g.:

DELETE /api/sites/1/devices/
[1, 2, 3]

Each object’s permissions are checked before deletion.

get_success_headers(data)[source]

Overload default to include relative request PATH.

Parameters:

data – Dict of validated serializer data

perform_create(serializer)[source]

Support bulk create.

Parameters:

serializer – Serializer instance

perform_destroy(instance)[source]

Overload default to handle non-serializer exceptions, and log Change events.

Parameters:

instance – Model instance to delete

perform_update(serializer)[source]

Overload default to handle non-serializer exceptions, and log Change events.

Parameters:

serializer – Serializer instance

class nsot.api.views.ProtocolTypeViewSet(**kwargs)[source]

API endpoint that allows ProtocolTypes to be viewed or edited.

filterset_class

alias of ProtocolTypeFilter

natural_key = 'name'

Natural key for the resource. If not defined, defaults to pk-only.

serializer_class

alias of ProtocolTypeSerializer

class nsot.api.views.ProtocolViewSet(**kwargs)[source]

API endpoint that allows Protocols to be viewed or edited.

filterset_class

alias of ProtocolFilter

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

serializer_class

alias of ProtocolSerializer

class nsot.api.views.ResourceViewSet(**kwargs)[source]

Resource views that include set query list endpoints.

get_resource_object(pk, site_pk)[source]

Return a resource object based on pk or site_pk.

query(request, site_pk=None, *args, **kwargs)[source]

Perform a set query.

class nsot.api.views.SiteViewSet(**kwargs)[source]

API endpoint that allows Sites to be viewed or edited.

serializer_class

alias of SiteSerializer

class nsot.api.views.UserPkInfo(user, pk)

Namedtuple for retrieving pk and user object of current user.

pk

Alias for field number 1

user

Alias for field number 0

class nsot.api.views.UserViewSet(**kwargs)[source]

This viewset automatically provides list and detail actins.

retrieve(request, pk=None, site_pk=None, *args, **kwargs)[source]

Retreive a single user.

serializer_class

alias of UserSerializer

class nsot.api.views.ValueViewSet(**kwargs)[source]

API endpoint that allows Attribute Values to be viewed or edited.

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

serializer_class

alias of ValueSerializer

Serializers

class nsot.api.serializers.AssignmentSerializer(*args, **kwargs)[source]

Used for GET on Assignments (address-to-interface bindings).

class nsot.api.serializers.AttributeCreateSerializer(*args, **kwargs)[source]

Used for POST on Attributes.

create(validated_data)[source]

We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just:

return ExampleModel.objects.create(**validated_data)

If there are many to many fields present on the instance then they cannot be set until the model is instantiated, in which case the implementation is like so:

example_relationship = validated_data.pop(‘example_relationship’) instance = ExampleModel.objects.create(**validated_data) instance.example_relationship = example_relationship return instance

The default implementation also does not handle nested relationships. If you want to support writable nested relationships you’ll need to write an explicit .create() method.

read_serializer_class

alias of AttributeSerializer

validate_depends_on(value)[source]

Resolve dependency names scoped to the same site and resource_name.

SlugRelatedField with an unscoped queryset may match wrong attributes when the same name exists across sites/resource_names. Re-resolve here using the request data for proper scoping.

class nsot.api.serializers.AttributeDefaultField(*args, **kwargs)[source]

Custom field for Attribute.default property.

Handles serialization of the default value which can be a string (single) or list of strings (multi).

to_internal_value(data)[source]

Transform the incoming primitive data into a native value.

to_representation(value)[source]

Transform the outgoing native value into primitive data.

class nsot.api.serializers.AttributeSerializer(*args, **kwargs)[source]

Used for GET, DELETE on Attributes.

class nsot.api.serializers.AttributeUpdateSerializer(*args, **kwargs)[source]

Used for PUT, PATCH, on Attributes.

Currently because Attributes have only one required field (name), and it may not be updated, there is not much functional difference between PUT and PATCH.

validate_depends_on(value)[source]

Re-resolve dependency names scoped to the instance’s site/resource_name.

class nsot.api.serializers.AuthTokenSerializer(*args, **kwargs)[source]

AuthToken authentication serializer to validate username/secret_key inputs.

class nsot.api.serializers.ChangeSerializer(*args, **kwargs)[source]

Used for displaying Change events.

to_representation(obj)[source]

Use DRF’s standard field-based serialization.

class nsot.api.serializers.CircuitCreateSerializer(*args, **kwargs)[source]

Used for POST on Circuits.

read_serializer_class

alias of CircuitSerializer

class nsot.api.serializers.CircuitPartialUpdateSerializer(*args, **kwargs)[source]

Used for PATCH on Circuits.

class nsot.api.serializers.CircuitSerializer(*args, **kwargs)[source]

Used for GET, DELETE on Circuits

class nsot.api.serializers.CircuitUpdateSerializer(*args, **kwargs)[source]

Used for PUT on Circuits.

class nsot.api.serializers.DeviceCreateSerializer(*args, **kwargs)[source]

Used for POST on Devices.

read_serializer_class

alias of DeviceSerializer

class nsot.api.serializers.DevicePartialUpdateSerializer(*args, **kwargs)[source]

Used for PATCH on Devices.

class nsot.api.serializers.DeviceSerializer(*args, **kwargs)[source]

Used for GET, DELETE on Devices.

class nsot.api.serializers.DeviceUpdateSerializer(*args, **kwargs)[source]

Used for PUT on Devices.

class nsot.api.serializers.InterfaceCreateSerializer(*args, **kwargs)[source]

Used for POST on Interfaces.

read_serializer_class

alias of InterfaceSerializer

class nsot.api.serializers.InterfacePartialUpdateSerializer(*args, **kwargs)[source]

Used for PATCH on Interfaces.

class nsot.api.serializers.InterfaceSerializer(*args, **kwargs)[source]

Used for GET, DELETE on Interfaces.

create(validated_data)[source]

Overload default create to handle setting of addresses.

update(instance, validated_data)[source]

Overload default update to handle setting of addresses.

validate_parent_id(value)[source]

Cast the parent_id to an int if it’s an Interface object.

class nsot.api.serializers.InterfaceTypeField(*args, **kwargs)[source]

Accepts integer type IDs or string type names (e.g. 6 or “ethernet”).

to_internal_value(data)[source]

Transform the incoming primitive data into a native value.

to_representation(value)[source]

Transform the outgoing native value into primitive data.

class nsot.api.serializers.InterfaceUpdateSerializer(*args, **kwargs)[source]

Used for PUT on Interfaces.

class nsot.api.serializers.JSONDataField(*args, **kwargs)[source]

Base field used to represent attributes as JSON <-> field_type.

It is an error if field_type is not defined in a subclass.

to_internal_value(data)[source]

Transform the incoming primitive data into a native value.

to_representation(value)[source]

Transform the outgoing native value into primitive data.

class nsot.api.serializers.JSONDictField(*args, **kwargs)[source]

Field used to represent attributes as JSON <-> Dict.

field_type

alias of dict

class nsot.api.serializers.JSONListField(*args, **kwargs)[source]

Field used to represent attributes as JSON <-> List.

field_type

alias of list

class nsot.api.serializers.MACAddressField(*args, **kwargs)[source]

Field used to validate MAC address objects as integer or string.

to_internal_value(value)[source]

Transform the incoming primitive data into a native value.

to_representation(value)[source]

Transform the outgoing native value into primitive data.

class nsot.api.serializers.NaturalKeyRelatedField(*args, **kwargs)[source]

Field that takes either a primary key or a natural key.

get_queryset()[source]

Attempt to filter queryset by site_pk.

to_internal_value(value)[source]

Try PK followed by slug (natural key) value.

to_representation(value)[source]

Transform the outgoing native value into primitive data.

class nsot.api.serializers.NetworkCreateSerializer(*args, **kwargs)[source]

Used for POST on Networks.

read_serializer_class

alias of NetworkSerializer

class nsot.api.serializers.NetworkPartialUpdateSerializer(*args, **kwargs)[source]

Used for PATCH on Networks.

class nsot.api.serializers.NetworkSerializer(*args, **kwargs)[source]

Used for GET, DELETE on Networks.

class nsot.api.serializers.NetworkUpdateSerializer(*args, **kwargs)[source]

Used for PUT on Networks.

class nsot.api.serializers.NsotSerializer(*args, **kwargs)[source]

Base serializer that logs change events.

to_internal_value(data)[source]

Inject site_pk from view’s kwargs if it’s not already in data.

to_representation(obj)[source]

Use DRF’s standard field-based serialization.

class nsot.api.serializers.ProtocolCreateSerializer(*args, **kwargs)[source]

Used for POST on Protocols.

read_serializer_class

alias of ProtocolSerializer

class nsot.api.serializers.ProtocolPartialUpdateSerializer(*args, **kwargs)[source]

Used for PATCH on Protocols.

class nsot.api.serializers.ProtocolSerializer(*args, **kwargs)[source]

Used for GET, DELETE on Protocols

class nsot.api.serializers.ProtocolTypeSerializer(*args, **kwargs)[source]

Used for all CRUD operations on ProtocolTypes.

class nsot.api.serializers.ProtocolUpdateSerializer(*args, **kwargs)[source]

Used for PUT on Protocols.

class nsot.api.serializers.ResourceSerializer(*args, **kwargs)[source]

For any object that can have attributes.

create(validated_data, commit=True)[source]

Create that is aware of attributes.

get_merged_attributes(obj)[source]

Return merged attributes if ?include_inherited=true.

update(instance, validated_data, commit=True)[source]

Update that is aware of attributes.

This will not set attributes if they are not provided during a partial update.

class nsot.api.serializers.SiteSerializer(*args, **kwargs)[source]
class nsot.api.serializers.UserSerializer(*args, **kwargs)[source]

UserProxy model serializer that takes optional with_secret_key argument that controls whether the secret_key for the user should be displayed.

class nsot.api.serializers.ValueCreateSerializer(*args, **kwargs)[source]

Used for POST on Values.

class nsot.api.serializers.ValueSerializer(*args, **kwargs)[source]

Used for GET, DELETE on Values.

class nsot.api.serializers.WriteSerializerMixin[source]

Mixin for create/update serializers that delegates read output to the corresponding read serializer.

Subclasses must define read_serializer_class pointing to the read serializer whose output format should be used for to_representation.

This mixin also disables FlexFieldsSerializerMixin behaviour (?fields, ?omit, ?expand) during deserialization so that query-parameter driven field removal/expansion cannot strip required fields (e.g. site_id) from write payloads.

get_fields()[source]

Bypass flex-fields apply_flex_fields during deserialization.

FlexFieldsSerializerMixin.get_fields calls apply_flex_fields which can pop required fields from the field map when ?fields or ?omit query parameters are present. Write serializers must always expose the full set of declared fields so that to_internal_value receives all expected inputs.

Filters

class nsot.api.filters.ChangeFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Filter for Change objects.

class nsot.api.filters.CircuitFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Filter for Circuit objects.

filter_device_hostname(queryset, name, value)[source]

Filter circuits by device hostname on either endpoint.

filter_endpoint_a(queryset, name, value)[source]

Overload to use natural key.

filter_endpoint_z(queryset, name, value)[source]

Overload to use natural key.

class nsot.api.filters.DeviceFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Filter for Device objects.

class nsot.api.filters.InterfaceFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Filter for Interface objects.

Includes a custom override for filtering on mac_address because this is not a Django built-in field.

filter_mac_address(queryset, name, value)[source]

Overloads queryset filtering to use built-in.

Doesn’t work by default because MACAddressField is not a Django built-in field type.

class nsot.api.filters.NetworkFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Filter for Network objects.

filter_cidr(queryset, name, value)[source]

Converts cidr to network/prefix filter.

filter_include_ips(queryset, name, value)[source]

Converts include_ips to queryset filters.

filter_include_networks(queryset, name, value)[source]

Converts include_networks to queryset filters.

filter_root_only(queryset, name, value)[source]

Converts root_only to null parent filter.

class nsot.api.filters.ProtocolFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Filter for Protocol objects.

filter_circuit(queryset, name, value)[source]

Overload to use natural key.

filter_device(queryset, name, value)[source]

Overload to use natural key.

filter_interface(queryset, name, value)[source]

Overload to use natural key.

filter_type(queryset, name, value)[source]

Overload to use natural key.

class nsot.api.filters.ProtocolTypeFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Filter for ProtocolType (non-resource) objects.

class nsot.api.filters.ResourceFilter(data=None, queryset=None, *, request=None, prefix=None)[source]

Attribute-aware filtering for Resource objects.

filter_attributes(queryset, name, value)[source]

Reads ‘attributes’ from query params and joins them together as an intersection set query.

When an attribute is marked as inheritable, resources that inherit the value from an ancestor (i.e. they don’t have their own explicit value but an ancestor does) are included in the results.

filter_expired(queryset, name, value)[source]

Delegate to the queryset’s .expired() method.

Pagination

Routers

class nsot.api.routers.BulkNestedRouter(*args, **kwargs)[source]

Bulk-enabled nested router.

class nsot.api.routers.BulkRouter(*args, **kwargs)[source]

Map http methods to actions defined on the bulk mixins.

URLs

Authentication

class nsot.api.auth.AuthTokenAuthentication[source]
authenticate(request)[source]

Authenticate the request and return a two-tuple of (user, token).

authenticate_header(request)[source]

Return a string to be used as the value of the WWW-Authenticate header in a 401 Unauthenticated response, or None if the authentication scheme should return 403 Permission Denied responses.

class nsot.api.auth.EmailHeaderAuthentication[source]
authenticate(request)[source]

Authenticate the request and return a two-tuple of (user, token).

class nsot.api.auth.SecretKeyAuthentication[source]

Utilities

Utilities used across the project.

class nsot.util.SetQuery(action, name, value)
action

Alias for field number 0

name

Alias for field number 1

value

Alias for field number 2

nsot.util.calculate_network_utilization(parent, hosts, as_string=False)[source]

Calculate utilization for a network and its descendants.

Parameters:
  • parent – The parent network

  • hosts – List of host IPs descendant from parent

  • as_string – Whether to return stats as a string

nsot.util.cidr_to_dict(cidr)[source]

Take a cidr and return it as a dictionary.

>>> cidr_to_dict('192.168.0.0/16')
{'network_address': '192.168.0.0', 'prefix_length': 16}
Parameters:

cidr – IPv4/IPv6 CIDR string

nsot.util.generate_secret_key()[source]

Return a secret key suitable for use w/ Fernet.

>>> generate_secret_key()
'1BpuqeM5d5pi-U2vIsqeQ8YnTrXRRUAfqV-hu6eQ5Gw='
nsot.util.generate_settings(config_template=None)[source]

Used to emit a generated configuration from config_template.

Parameters:

config_template – Config template

nsot.util.get_field_attr(model, field_name, attr_name)[source]

Return the specified attribute value from a model field.

This is used for field overrides in API serializers to retrieve the verbose_name and help_text model field attributes so they don’t need to be duplicated in code.

Example:

>>> get_field_attr(models.Interface, 'parent', 'help_text')
'Unique ID of the parent Interface.'
Parameters:
  • model – Model class

  • field_name – Model field name

  • attr_name – Model field attribute name

nsot.util.get_network_utilization(network, as_string=False)[source]

Get utilization from Network instance.

Parameters:
  • network – A Network model instance

  • as_string – Whether to return stats as a string

nsot.util.initialize_app(config)[source]

Actions to be performed prior to creating the Application object.

Parameters:

config – Config object

nsot.util.main()[source]

CLI application used to manage NSoT.

nsot.util.normalize_auth_header(header)[source]

Normalize a header name into WSGI-compatible format.

>>> normalize_auth_header('X-NSoT-Email')
'HTTP_X_NSOT_EMAIL'
Parameters:

header – Header name

nsot.util.parse_set_query(query)[source]

Parse a representation of set operations for attribute/value pairs into (action, name, value) and return a list of SetQuery objects.

Computes left-to-right evaluation, where the first character indicates the set operation:

  • “+” indicates a union

  • “-” indicates a difference

  • no marker indicates an intersection

For example:

>>> parse_set_query('+owner=team-networking')
[SetQuery(action='union', name='owner', value='team-networking')]
>>> parse_set_query('foo=bar')
[SetQuery(action='intersection', name='foo', value='bar')]
>>> parse_set_query('foo=bar -owner=team-networking')
[SetQuery(action='intersection', name='foo', value='bar'),
 SetQuery(action='difference', name='owner', value='team-networking')]
Parameters:

query – Set query string

nsot.util.qpbool(arg)[source]

Convert “truthy” strings into Booleans.

>>> qpbool('true')
True
Parameters:

arg – Truthy string

nsot.util.slugify(s)[source]

Slugify a string.

This works in a less-agressive manner than Django’s slugify, which simply drops most drops most non-alphanumeric characters and lowercases the entire string. It would likely to cause uniqueness conflicts for things like interface names, such as Eth1/2/3 and Eth12/3, which would slugify to be the same.

>>> slugify('switch-foo01:Ethernet1/2')
'switch-foo01:Ethernet1_2'
Parameters:

s – String to slugify

nsot.util.slugify_interface(interface=None, device_hostname=None, name=None, **kwargs)[source]

Return a slug (natural key) representation of an Interface.

If interface is not provided, device_hostname and name are required. If all are provided, interface will take precedence.

Parameters:
  • interface – Interface dict

  • device_hostname – Device hostname

  • name – Interface name

Return type:

str