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.

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.

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_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.NetworkManager[source]

Manager for NetworkInterface objects.

get_by_address(cidr, site=None)[source]

Lookup a Network object by cidr.

Parameters:
  • cidr – IPv4/IPv6 CIDR string
  • siteSite instance or site_id
get_closest_parent(cidr, prefix_length=0, site=None)[source]

Return the closest matching parent Network for a cidr even if it doesn’t exist in the database.

Parameters:
  • cidr – IPv4/IPv6 CIDR string
  • prefix_length – Maximum prefix length depth for closest parent lookup
  • siteSite instance or site_id
class nsot.models.Resource(*args, **kwargs)[source]

Base for heirarchial Resource objects that may have attributes.

clean_attributes()[source]

Make sure that attributes are saved as JSON.

get_attributes()[source]

Return the JSON-encoded attributes as a dict.

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

Validate and store the attributes dict as a JSON-encoded string.

class nsot.models.ResourceManager[source]

Manager for Resource objects that adds a special resource methods:

  • .set_query() - For performing set theory lookups by attribute-value string patterns
  • .by_attribute() - For looking up objects by attribute name/value.
by_attribute(name, value, site_id=None)[source]

Filter objects by Attribute name and value.

For example:

>>> Interface.objects.by_attribute(name='vlan', value=300)
[<Interface: device=1, name=eth0>]
Parameters:
  • name – Attribute name
  • value – Attribute value
  • site_id – ID of Site to filter results
queryset_class

alias of ResourceSetTheoryQuerySet

set_query(query, site_id=None, unique=False)[source]

Filter objects by set theory attribute-value string patterns.

For example:

>>> Network.objects.set_query('owner=jathan +cluster=sjc'}
[<Device: foo-bar1>, <Device: foo-bar3>, <Device: foo-bar4>]

>>> Network.objects.set_query('owner=gary -cluster=sjc'}
[<Device: foo-bar2>]

>>> Network.objects.set_query('owner=jathan foo=baz', unique=True}
[<Device: foo-bar3>]
Parameters:
  • query – Set theory query pattern
  • site_id – ID of Site to filter results
  • unique – Find exactly one match, error otherwise
class nsot.models.ResourceSetTheoryQuerySet(model=None, query=None, using=None, hints=None)[source]

Set theory QuerySet for Resource objects to add .set_query() method.

For example:

>>> qs = Network.objects.filter(network_address=u'10.0.0.0')
>>> qs.set_query('owner=jathan +metro=lax')

You may also search using regex by appending _regex to an attribtue name and providing a regex pattern as the value:

>>> qs = Device.objects.set_query('role_regex=[bd]r')

Which is functionally equivalent to:

>>> qs = Device.objects.set_query('role=br +role=dr')
by_attribute(name, value, site_id=None)[source]

Lookup objects by Attribute name and value.

set_query(query, site_id=None, unique=False)[source]

Filter objects by set theory attribute-value query patterns.

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.

nsot.models.change_api_updated_at(sender=None, instance=None, *args, **kwargs)[source]

Anytime the API is updated, invalidate the cache.

nsot.models.delete_resource_values(sender, instance, **kwargs)[source]

Delete values when a Resource object is deleted.

nsot.models.model_class

alias of Circuit

nsot.models.update_device_interfaces(sender, instance, **kwargs)[source]

Anytime a device is saved, update device_hostname on its interfaces

Fields

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

IP Address field that stores values as varbinary.

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

Python -> DB.

to_python(value)[source]

DB -> Python.

class nsot.fields.ChainedForeignKey(to, chained_field=None, chained_model_field=None, show_all=False, auto_choose=False, sort=True, view_name=None, **kwargs)[source]

chains the choices of a previous combo box with this one

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

south_field_triple()[source]

Returns a suitable description of this field for South.

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/2ilboIQ

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

Return a list of devices for this Circuit.

filter_class

alias of CircuitFilter

get_natural_key_kwargs(filter_value)[source]

Return a dict of kwargs for natural_key lookup.

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

get_natural_key_kwargs(filter_value)[source]

Return a dict of kwargs for natural_key lookup.

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

get_natural_key_kwargs(filter_value)[source]

Return a dict of kwargs for natural_key lookup.

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

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

Filter for Circuit objects.

class nsot.api.filters.DeviceFilter(*args, **kwargs)[source]

Filter for Device objects.

class nsot.api.filters.InterfaceFilter(*args, **kwargs)[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, 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(*args, **kwargs)[source]

Filter for Network objects.

filter_cidr(queryset, value)[source]

Converts cidr to network/prefix filter.

filter_include_ips(queryset, value)[source]

Converts include_ips to queryset filters.

filter_include_networks(queryset, value)[source]

Converts include_networks to queryset filters.

filter_root_only(queryset, value)[source]

Converts root_only to null parent filter.

class nsot.api.filters.ResourceFilter(*args, **kwargs)[source]

Attribute-aware filtering for Resource objects.

filter_attributes(queryset, 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

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

Return the specified field for a model field

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