API

This part of the documentation is for API reference

Clients

Simple Python API client for NSoT REST API.

The easiest way to get a client is to call get_api_client() with no arguments. This will read the user’s ~/.pynsotrc file and pass the values to the client constructor:

>>> from pynsot.client import get_api_client
>>> api = get_api_client()
>>> api
AuthTokenClient(url=http://localhost:8990/api)>
pynsot.client.get_api_client(auth_method=None, url=None, extra_args=None, use_dotfile=True)[source]

Safely create an API client so that users don’t see tracebacks.

Any arguments taht aren’t explicitly passed will be replaced by the contents of the user’s dotfile.

Parameters:
  • auth_method – Auth method used by the client
  • url – API URL
  • extra_args – Dict of extra keyword args to be passed to the API client class
  • use_dotfile – Whether to read the dotfile or not.
class pynsot.client.BaseClient(base_url=None, **kwargs)[source]

Magic REST API client for NSoT.

error(exc)[source]

Take errors and make them human-readable.

Parameters:exc – Exception instance
get_auth(**kwargs)[source]

Subclasses should references kwargs from self._kwargs.

Parameters:client – Client instance. Defaults to self.
get_resource(resource_name)[source]

Return a single resource object.

Parameters:resource_name – Name of resource
class pynsot.client.EmailHeaderClient(base_url=None, **kwargs)[source]

Default client using email auth header method.

authentication_class

alias of EmailHeaderAuthentication

class pynsot.client.AuthTokenClient(base_url=None, **kwargs)[source]

Client that uses auth_token method.

authentication_class

alias of AuthTokenAuthentication

class pynsot.client.BaseClientAuth(client)[source]
append_api_version(request)[source]

Append API version into Accept header.

class pynsot.client.EmailHeaderAuthentication(client)[source]

Special authentication that sets the email auth header.

classmethod get_user()[source]

Get the local username, or if root, the sudo username.

class pynsot.client.AuthTokenAuthentication(client)[source]

Special authentication that utilizes auth_tokens.

Adds header for “Authorization: ApiToken {email}:{auth_token}”

get_token(base_url, email, secret_key)[source]

Currently ghetto: Hit the API to get an auth_token.

Parameters:
  • base_url – API URL
  • email – User’s email
  • secret_key – User’s secret_key

API Models

API Model Classes

These resource models are derrived from collections.MutableMapping and, thus, act like dicts and can instantiate with raw resource output from API as well as simplifying by providing site_id and (usually) the natural key (cidr, hostname, etc).

Example

>>> from pynsot.models import Network, Device, Interface
>>> from pynsot.client import get_api_client
>>> client = get_api_client()
>>> net = Network(raw=client.networks.get()[-1])
>>>
>>> # Or also...
>>> # >>> net = Network(client=client, site_id=1, cidr='8.8.8.0/24')
>>>
>>> net.exists()
>>> True
>>>
>>> net.existing_resource()
{u'attributes': {},
 u'id': 81,
 u'ip_version': u'4',
 u'is_ip': False,
 u'network_address': u'254.0.0.0',
 u'parent_id': 1,
 u'prefix_length': 24,
 u'site_id': 1,
 u'state': u'allocated'}
>>>
>>> net.purge()
True
>>>
>>> net.exists()
False
>>>
>>> net.ensure()
True
>>>
>>> net.exists()
True
>>>
>>> net['site_id']
2
>>>
>>> net['site_id'] = 4
>>>
>>> net.exists()
False
>>>
>>> net['site_id'] = 2
>>>
>>> net.exists()
True
class pynsot.models.Resource(site_id=None, client=None, raw=None, attributes=None, **kwargs)[source]

Base API Abstraction Models Class

Instances of an API abstraction model represent a single NSoT resource and provide methods for managing the state of it upstream. They can be instantiated by the raw returned object from NSoT API or more simply by a few descriptive kwargs.

Resource is a subclass of :class:collections.MutableMapping which makes it act as a dictionary would. The mapping represents the payload that would be accepted by NSoT and can be manipulated as desired like a normal dict.

Subclassing:
Subclasses must adhere to a simple contract:
  • Overload the abstractmethods and abstractproperties this class uses
  • If custom arguments are needed, overload self.postinit. Just make sure to call self.init_payload() at the end. All kwargs that aren’t handled by self.__init__ are passed here
Parameters:
  • site_id (int) – Site ID this reseource belongs to. Required unless raw is supplied.
  • attributes (dict) –

    Attributes to add to resource. If supplying raw, add these after the instantiation like:

    >>> obj = Device(raw=RAW_API_DICT)
    >>> obj['attributes'] = {}
    
  • client (pynsot.client.BaseClient) – Pynsot client for API interactions. Will be lazily loaded if not provided, but might be cheaper to supply it up front.
  • raw (dict) – Raw NSoT resource object. What would be returned from a GET, POST, PUT, or PATCH operation for a single resource. Gets mapped directly to payload
clear_cache()[source]

Clears state of certain properties

This is ideally done during a write operation against the API, such as .purge() or .ensure(). Helps prevent representing out-of-date information

ensure()[source]

Ensure object in current state exists in NSoT

By site, make sure resource exists. True if it is or was able to get to the desired state, False if not and logged in last_error.

Having this operation be done individually for each resource has some pros and cons. Generally as long as the amount of items is small enough, it’s not a huge difference but it is an extra HTTP request.

Sending in bulk halts at the first error and fails the following so it requires more handling.

Cache is cleared first thing and before return.

Return type:bool
ensure_client(**kwargs)[source]

Ensure that object has a client object

Client may be passed during __init__ as a kwarg, but call this before doing any client work to ensure

Parameters:kwargs (dict) – These will be passed to get_api_client.
existing_resource()[source]

Returns upstream resource

If nothing exists, empty dict is returned. The result of this is cached in a property (_existing_resource) for cheaper re-checks. This can be cleared via .clear_cache()

Return type:dict
exists()[source]

Does the current resource exist?

Return type:bool
identifier

Human-friendly string to represent the resource

Used in log messages and magic methods for comparison. Examples here would be CIDR, hostname, etc

Return type:str
init_payload()[source]

Initializes the payload dictionary using resource specific data

log_error(error)[source]

Log and append errors to object

This does a check to see if response object available from HTTP request. If not, that’s OK too and it’ll just append the raw error.

payload

Represents exact payload sent to NSoT server

Returns:_payload
Return type:dict
postinit(**kwargs)[source]

Overloadable method for post __init__

Use this for things that need to happen post-init, including subclass-specific argument handling.

This method is called at the very end of __init__ unless raw is given.

Params kwargs:All unhandled kwargs from __init__ are passed here
purge()[source]

Ensure resource doesn’t exist upstream

By site, make sure resource is deleted. True if it is or was able to get to the desired state, False if not and logged in last_error.

Cache is cleared first thing and before return.

Return type:bool
resource

Pynsot client for resource type

Return type:pynsot.client.BaseClient
resource_name

Name of resource

Must be plural

Return type:str
class pynsot.models.Network(site_id=None, client=None, raw=None, attributes=None, **kwargs)[source]

Network API Abstraction Model

Subclass of Resource.

>>> n = Network(cidr='8.8.8.0/24', site_id=1)
>>> n.exists()
False
>>> n.ensure()
True
>>> n.exists()
True
>>> n.existing_resource()
{u'attributes': {},
 u'id': 31,
 u'ip_version': u'4',
 u'is_ip': True,
 u'network_address': u'8.8.8.0',
 u'parent_id': 1,
 u'prefix_length': 24,
 u'site_id': 1,
 u'state': u'assigned'}
>>>
>>> n.purge()
True
>>> n.exists()
False
>>> n.closest_parent()
<Network: 8.8.0.0/16>
Parameters:cidr – CIDR for network
closest_parent()[source]

Returns resource object of the closest parent network

Empty dictionary if no parent network

Returns:Parent resource
Return type:pynsot.models.Network or dict
init_payload()[source]

This will init the payload property

class pynsot.models.Device(site_id=None, client=None, raw=None, attributes=None, **kwargs)[source]

Device Resource

Subclass of Resource.

>>> dev = Device(hostname='router1-nyc', site_id=1)
>>> dev.exists()
False
>>>
>>> dev.ensure()
True
>>>
>>> dev.existing_resource()
{u'attributes': {}, u'hostname': u'router1-nyc', u'id': 1, u'site_id': 1}
>>> dev.purge()
True
>>>
>>> dev.exists()
False
Parameters:hostname – Device hostname
class pynsot.models.Interface(site_id=None, client=None, raw=None, attributes=None, **kwargs)[source]

Interface Resource

Subclass of Resource

Parameters:
  • addresses (list) – Addresses on interface
  • description – Interface description
  • device (pynsot.models.Device) – Required, device interface is on. TODO: broken as currently implemented but will soon reflect the following type
  • type (int) – Interface type as described by SNMP IF-TYPE’s
  • mac_address – MAC of interface
  • name – Required, name of interface
  • parent_id (int) – ID of parent interface
  • speed (int) – Speed of interface
attempt_device()[source]

Attempt to set device attribute to its ID if hostname was given

If an ID was provided during init, this happens in init. If a hostname was provided, we need to take care of a couple things.

  1. Attempt to fetch ID for existing device by the hostname. If this works, use this ID

  2. Should #1 fail, set device id to 0 to signify this device doesn’t exist yet, hoping this method will be called again when it’s time to create. The thought here is if a user is instantiating lots of resources at the same time, there’s a chance the device this relates to is going to be created before this one actually gets called upon.

    0 is used instead of a more descriptive message because should the device still not exist when executing this, at least a device doesn’t exist error would be returned instead of expecting int not str.

Utilities

pynsot.util.get_result(response)[source]

Get the desired result from an API response.

Parameters:response – Requests API response object

Dotfile

class pynsot.dotfile.Dotfile(filepath=u'/home/docs/.pynsotrc', **kwargs)[source]

Create, read, and write a dotfile.