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_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_fields(exclude=None)[source]¶
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
- property default¶
Get the default value, unwrapping from internal storage format.
- class nsot.models.Change(*args, **kwargs)[source]¶
Record of all changes in NSoT.
- exception DoesNotExist¶
- exception MultipleObjectsReturned¶
- 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.
- 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_fields(exclude=None)[source]¶
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
- 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.
- class nsot.models.Network(*args, **kwargs)[source]¶
Represents a subnet or IP address.
- exception DoesNotExist¶
- exception MultipleObjectsReturned¶
- 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)
- class nsot.models.Protocol(*args, **kwargs)[source]¶
Representation of a routing protocol
- 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.
- class nsot.models.ProtocolType(*args, **kwargs)[source]¶
Representation of protocol types (e.g. bgp, is-is, ospf, etc.)
- exception DoesNotExist¶
- exception MultipleObjectsReturned¶
- 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.AbstractEmailUserbase class with an equivalent inline implementation based onAbstractBaseUserandPermissionsMixin.- 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.
- 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.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.
- 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.
- 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.
Validators¶
Validators for validating object fields.
Exceptions¶
- nsot.exc.DjangoValidationError¶
alias of
ValidationError
- exception nsot.exc.ModelError(detail=None, code=None)[source]¶
Base class for NSoT Model Exceptions.
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.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 anatural_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
siteinto filter lookup ifsite_pkis 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.
- 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
- 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_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.
- 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.
- root(request, pk=None, site_pk=None, *args, **kwargs)[source]¶
Return the parent of all ancestors for this Network.
- serializer_class¶
alias of
NetworkSerializer
- 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)
- 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
- 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.
- 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.
- 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
- 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).
- 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.
- 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.
- 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.
- class nsot.api.serializers.InterfaceTypeField(*args, **kwargs)[source]¶
Accepts integer type IDs or string type names (e.g. 6 or “ethernet”).
- 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_typeis not defined in a subclass.
- 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.
- class nsot.api.serializers.NaturalKeyRelatedField(*args, **kwargs)[source]¶
Field that takes either a primary key or a natural key.
- 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.
- 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.
- 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.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_classpointing to the read serializer whose output format should be used forto_representation.This mixin also disables
FlexFieldsSerializerMixinbehaviour (?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_fieldsduring deserialization.FlexFieldsSerializerMixin.get_fieldscallsapply_flex_fieldswhich can pop required fields from the field map when?fieldsor?omitquery parameters are present. Write serializers must always expose the full set of declared fields so thatto_internal_valuereceives 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.
- 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.
- class nsot.api.filters.NetworkFilter(data=None, queryset=None, *, request=None, prefix=None)[source]¶
Filter for Network objects.
- class nsot.api.filters.ProtocolFilter(data=None, queryset=None, *, request=None, prefix=None)[source]¶
Filter for Protocol objects.
- 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.
Pagination¶
Routers¶
URLs¶
Authentication¶
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_nameandhelp_textmodel 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.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
SetQueryobjects.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
interfaceis not provided,device_hostnameandnameare required. If all are provided,interfacewill take precedence.- Parameters:
interface – Interface dict
device_hostname – Device hostname
name – Interface name
- Return type:
str