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.

clean_address(value)[source]

Enforce that new addresses can only be host addresses.

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

Represents a flexible attribute for Resource objects.

clean_constraints(value)[source]

Enforce formatting of constraints.

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

Always enforce constraints.

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

Record of all changes in NSoT.

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.

diff

Return the diff of the JSON representation of the cached copy of a Resource with its current instance

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

Represents two network Interfaces that are connected

addresses

Return addresses associated with this circuit.

clean_site(value)[source]

Always enforce that site is set.

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

interfaces

Return interfaces associated with this circuit.

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

Represents a network device.

circuits

All circuits related to this Device.

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

A network interface.

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
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_mac_address(value)[source]

Enforce valid mac_address.

clean_name(value)[source]

Enforce name.

clean_name_slug(value=None)[source]

Slugify the interface name into natural key.

clean_site(value)[source]

Always enforce that site is set.

clean_speed(value)[source]

Enforce valid speed.

clean_type(value)[source]

Enforce valid type.

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.

networks

Return all the parent Networks for my addresses.

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.

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=None, 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=None, 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

clean_circuit(value)[source]

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

clean_interface(value)[source]

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

clean_site(value)[source]

Ensure we have a site set. If one is not explicitly set, glean it from the device. If the device has none, then raise a ValidationError

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.)

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.

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

A custom user object that utilizes email as the username.

generate_auth_token()[source]

Serialize user data and encrypt token.

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.

clean_site(value)[source]

Always enforce that site is set.

Fields

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

IP Address field that stores values as varbinary.

from_db_value(value, expression, connection, context)[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.

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

Convert our JSON object to a string before we save

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.

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.Error(detail=None, code=None)[source]

Baseclass for NSoT Exceptions.

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

Base class for NSoT Model Exceptions.

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

Base HTTP error.

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

HTTP 400 error.

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

HTTP 401 error.

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

HTTP 403 error.

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

HTTP 404 error.

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

HTTP 409 error.

nsot.exc.DjangoValidationError

alias of ValidationError

exception nsot.exc.ObjectDoesNotExist[source]

The requested object does not exist

exception nsot.exc.MultipleObjectsReturned[source]

The query returned multiple objects when only one was expected.

REST API Primitives

Views

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

API endpoint that allows Attributes to be viewed or edited.

serializer_class

alias of AttributeSerializer

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, *args, **kwargs)[source]

List objects optionally filtered by site.

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.

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.

filter_class

alias of CircuitFilter

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

Return a list of interfaces for this Circuit.

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

Override default list so we can cache results.

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

Override default retrieve so we can cache results.

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

filter_class

alias of DeviceFilter

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

Return all interfaces for this Device.

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.

filter_class

alias of InterfaceFilter

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

Override default list so we can cache results.

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.

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

Override default retrieve so we can cache results.

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.

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

Return descendants of this Network.

Deprecated since version 1.1.

This endpoint is pending deprecation. Use the descendants endpoint instead.

filter_class

alias of NetworkFilter

get_natural_key_kwargs(filter_value)[source]

Return a dict of kwargs for natural_key lookup.

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.

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.

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.

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.

filter_class

alias of ProtocolTypeFilter

serializer_class

alias of ProtocolTypeSerializer

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

API endpoint that allows Protocols to be viewed or edited.

filter_class

alias of ProtocolFilter

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.

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.

serializer_class

alias of ValueSerializer

Serializers

class nsot.api.serializers.AttributeCreateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for POST on Attributes.

class nsot.api.serializers.AttributeSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for GET, DELETE on Attributes.

class nsot.api.serializers.AttributeUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **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.

class nsot.api.serializers.AuthTokenSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

AuthToken authentication serializer to validate username/secret_key inputs.

class nsot.api.serializers.ChangeSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for displaying Change events.

class nsot.api.serializers.CircuitCreateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for POST on Circuits.

class nsot.api.serializers.CircuitPartialUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PATCH on Circuits.

class nsot.api.serializers.CircuitSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for GET, DELETE on Circuits

class nsot.api.serializers.CircuitUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PUT on Circuits.

class nsot.api.serializers.DeviceCreateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for POST on Devices.

class nsot.api.serializers.DevicePartialUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PATCH on Devices.

class nsot.api.serializers.DeviceSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for GET, DELETE on Devices.

class nsot.api.serializers.DeviceUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PUT on Devices.

class nsot.api.serializers.InterfaceCreateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for POST on Interfaces.

class nsot.api.serializers.InterfacePartialUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PATCH on Interfaces.

class nsot.api.serializers.InterfaceSerializer(instance=None, data=<class rest_framework.fields.empty>, **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.InterfaceUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PUT on Interfaces.

class nsot.api.serializers.JSONDataField(read_only=False, write_only=False, required=None, default=<class rest_framework.fields.empty>, initial=<class rest_framework.fields.empty>, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False)[source]

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

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

class nsot.api.serializers.JSONDictField(read_only=False, write_only=False, required=None, default=<class rest_framework.fields.empty>, initial=<class rest_framework.fields.empty>, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False)[source]

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

field_type

alias of dict

class nsot.api.serializers.JSONListField(read_only=False, write_only=False, required=None, default=<class rest_framework.fields.empty>, initial=<class rest_framework.fields.empty>, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False)[source]

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

field_type

alias of list

class nsot.api.serializers.MACAddressField(read_only=False, write_only=False, required=None, default=<class rest_framework.fields.empty>, initial=<class rest_framework.fields.empty>, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False)[source]

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

class nsot.api.serializers.NaturalKeyRelatedField(slug_field=None, **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.

class nsot.api.serializers.NetworkCreateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for POST on Networks.

class nsot.api.serializers.NetworkPartialUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PATCH on Networks.

class nsot.api.serializers.NetworkSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for GET, DELETE on Networks.

class nsot.api.serializers.NetworkUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PUT on Networks.

class nsot.api.serializers.NsotSerializer(instance=None, data=<class rest_framework.fields.empty>, **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]

Always return the dict representation.

class nsot.api.serializers.ProtocolCreateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for POST on Protocols.

class nsot.api.serializers.ProtocolPartialUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PATCH on Protocols.

class nsot.api.serializers.ProtocolSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for GET, DELETE on Protocols

class nsot.api.serializers.ProtocolTypeSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for all CRUD operations on ProtocolTypes.

class nsot.api.serializers.ProtocolUpdateSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for PUT on Protocols.

class nsot.api.serializers.ResourceSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

For any object that can have attributes.

create(validated_data, commit=True)[source]

Create that is aware of attributes.

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.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(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for POST on Values.

class nsot.api.serializers.ValueSerializer(instance=None, data=<class rest_framework.fields.empty>, **kwargs)[source]

Used for GET, DELETE on Values.

Filters

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

Filter for Circuit objects.

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, prefix=None, strict=None, request=None)[source]

Filter for Device objects.

class nsot.api.filters.InterfaceFilter(data=None, queryset=None, prefix=None, strict=None, request=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, prefix=None, strict=None, request=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, prefix=None, strict=None, request=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, prefix=None, strict=None, request=None)[source]

Filter for ProtocolType (non-resource) objects.

class nsot.api.filters.ResourceFilter(data=None, queryset=None, prefix=None, strict=None, request=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.

Routers

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

Map http methods to actions defined on the bulk mixins.

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

Bulk-enabled nested router.

Utilities

Utilities used across the project.

nsot.util.qpbool(arg)[source]

Convert “truthy” strings into Booleans.

>>> qpbool('true')
True
Parameters:arg – Truthy string
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.generate_secret_key()[source]

Return a secret key suitable for use w/ Fernet.

>>> generate_secret_key()
'1BpuqeM5d5pi-U2vIsqeQ8YnTrXRRUAfqV-hu6eQ5Gw='
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
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.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.generate_settings(config_template=None)[source]

Used to emit a generated configuration from config_template.

Parameters:config_template – Config template
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.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.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

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