Example #1
0
    def save(self):
        """Saves changes to an existing object.

        Runs self.serialize() and checks that it doesn't match
        self._compare(). If not create a Request object and run .put()

        :returns: True if PUT request was successful.
        :example:

        >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
        >>> x.serial
        u''
        >>> x.serial = '1234'
        >>> x.save()
        True
        >>>
        """
        if self.id:
            if not self._compare():
                req = Request(key=self.id,
                              base=self.endpoint_meta.get('url'),
                              token=self.api_kwargs.get('token'),
                              session_key=self.api_kwargs.get('session_key'),
                              version=self.api_kwargs.get('version'),
                              ssl_verify=self.api_kwargs.get('ssl_verify'))
                if req.put(self.serialize()):
                    return True
            else:
                return False
Example #2
0
    def all(self):
        """Queries the 'ListView' of a given endpoint.

        Returns all objects from an endpoint.

        :Returns: List of instantiated objects.

        :Examples:

        >>> nb.dcim.devices.all()
        [test1-a3-oobsw2, test1-a3-oobsw3, test1-a3-oobsw4]
        >>>
        """
        req = Request(
            base='{}/'.format(self.url),
            token=self.token,
            session_key=self.session_key,
            version=self.version,
            ssl_verify=self.ssl_verify,
        )
        ret_kwargs = dict(
            api_kwargs=self.api_kwargs,
            endpoint_meta=self.meta,
        )
        return [
            self.return_obj(i, **ret_kwargs)
            for i in req.get()
        ]
Example #3
0
    def filter(self, *args, **kwargs):
        r"""Queries the 'ListView' of a given endpoint.

        Takes named arguments that match the usable filters on a
        given endpoint. If an argument is passed then it's used as a
        freeform search argument if the endpoint supports it.

        :arg str,optional \*args: Freeform search string that's
            accepted on given endpoint.
        :arg str,optional \**kwargs: Any search argument the
            endpoint accepts can be added as a keyword arg.

        :Returns: A list of instantiated objects.

        :Examples:

        To return a list of objects matching a named argument filter.

        >>> nb.dcim.devices.filter(role='leaf-switch')
        [test1-a3-tor1b, test1-a3-tor1c, test1-a3-tor1d, test1-a3-tor2a]
        >>>

        Using a freeform query along with a named argument.

        >>> nb.dcim.devices.filter('a3', role='leaf-switch')
        [test1-a3-tor1b, test1-a3-tor1c, test1-a3-tor1d, test1-a3-tor2a]
        >>>

        Chaining multiple named arguments.

        >>> nb.dcim.devices.filter(role='leaf-switch', status=True)
        [test1-leaf2]
        >>>

        Passing a list as a named argument adds multiple filters of the
        same value.

        >>> nb.dcim.devices.filter(role=['leaf-switch', 'spine-switch'])
        [test1-a3-spine1, test1-a3-spine2, test1-a3-leaf1]
        >>>
        """

        if len(args) > 0:
            kwargs.update({'q': args[0]})

        req = Request(
            filters=kwargs,
            base=self.url,
            token=self.token,
            session_key=self.session_key,
            version=self.version,
            ssl_verify=self.ssl_verify,
        )
        ret_kwargs = dict(
            api_kwargs=self.api_kwargs,
            endpoint_meta=self.meta,
        )
        ret = [self.return_obj(i, **ret_kwargs) for i in req.get()]
        return ret
Example #4
0
    def get(self, *args, **kwargs):
        r"""Queries the DetailsView of a given endpoint.

        :arg int,optional key: id for the item to be
            retrieved.

        :arg str,optional \**kwargs: Accepts the same keyword args as
            filter(). Any search argeter the endpoint accepts can
            be added as a keyword arg.

        :returns: A single instantiated objects.

        :raises ValueError: if kwarg search return more than one value.

        :Examples:

        Referencing with a kwarg that only returns one value.

        >>> nb.dcim.devices.get(name='test1-a3-tor1b')
        test1-a3-tor1b
        >>>

        Referencing with an id.

        >>> nb.dcim.devices.get(1)
        test1-edge1
        >>>
        """
        try:
            key = args[0]
        except IndexError:
            key = None
        if not key:
            filter_lookup = self.filter(**kwargs)
            if len(filter_lookup) == 1:
                return filter_lookup[0]
            if len(filter_lookup) == 0:
                return None
            else:
                raise ValueError('get() returned more than one result.')

        req = Request(
            key=key,
            base=self.url,
            token=self.token,
            session_key=self.session_key,
            version=self.version,
            ssl_verify=self.ssl_verify,
        )
        ret_kwargs = dict(
            api_kwargs=self.api_kwargs,
            endpoint_meta=self.meta,
        )

        return self.return_obj(req.get(), **ret_kwargs)
Example #5
0
    def _create(self, data):
        """Base create method

        Used in .create() and .bulk_create()
        """

        req = Request(
            base=self.url,
            token=self.token,
            session_key=self.session_key,
            version=self.version,
        )
        post = req.post(data)
        if post:
            return post['id']
        else:
            return False
Example #6
0
    def full_details(self):
        """Queries the hyperlinked endpoint if 'url' is defined.

        This method will populate the attributes from the detail
        endpoint when it's called. Sets the class-level `has_details`
        attribute when it's called to prevent being called more
        than once.

        :returns: True
        """
        if self.url:
            req = Request(base=self.url,
                          version=self.api_kwargs.get('version'))
            self._parse_values(req.get())
            self.has_details = True
            return True
        return False
Example #7
0
    def create(self, *args, **kwargs):
        r"""Creates an object on an endpoint.

        Allows for the creation of new objects on an endpoint. Named
        arguments are converted to json properties, and a single object
        is created. NetBox's bulk creation capabilities can be used by
        passing a list of dictionaries as the first argument.

        .. note:

            Any positional arguments will supercede named ones.

        :arg list \*args: A list of dictionaries containing the
            properties of the objects to be created.
        :arg str \**kwargs: key/value strings representing
            properties on a json object.

        :returns: A response from NetBox as a dictionary or list of
            dictionaries.

        :Examples:

        Creating an object on the `devices` endpoint you can lookup a
        device_role's name with:

        >>> netbox.dcim.devices.create(
        ...    name='test',
        ...    device_role=1,
        ... )
        >>>

        Use bulk creation by passing a list of dictionaries:

        >>> nb.dcim.devices.create([
        ...     {
        ...         "name": "test1-core3",
        ...         "device_role": 3,
        ...         "site": 1,
        ...         "device_type": 1,
        ...         "status": 1
        ...     },
        ...     {
        ...         "name": "test1-core4",
        ...         "device_role": 3,
        ...         "site": 1,
        ...         "device_type": 1,
        ...         "status": 1
        ...     }
        ... ])
        """

        return Request(
            base=self.url,
            token=self.token,
            session_key=self.session_key,
            version=self.version,
            ssl_verify=self.ssl_verify,
        ).post(args[0] if len(args) > 0 else kwargs)
Example #8
0
    def list(self):
        """The view operation for a detail endpoint

        Returns the response from NetBox for a detail endpoint.

        :returns: A dictionary or list of dictionaries its retrieved
            from NetBox.
        """
        return Request(**self.request_kwargs).get()
Example #9
0
    def delete(self):
        """Deletes an existing object.

        :returns: True if DELETE operation was successful.
        :example:

        >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
        >>> x.delete()
        True
        >>>
        """
        req = Request(key=self.id,
                      base=self.endpoint_meta.get('url'),
                      token=self.api_kwargs.get('token'),
                      session_key=self.api_kwargs.get('session_key'),
                      version=self.api_kwargs.get('version'))
        if req.delete():
            return True
        else:
            return False
Example #10
0
    def create(self, data={}):
        """The write operation for a detail endpoint.

        Creates objects on a detail endpoint in NetBox.

        :arg dict/list,optional data: A dictionary containing the
            key/value pair of the items you're creating on the parent
            object. Defaults to empty dict which will create a single
            item with default values.

        :returns: A dictionary or list of dictionaries its created in
            NetBox.
        """
        return Request(**self.request_kwargs).post(data)
Example #11
0
    def list(self, **kwargs):
        r"""The view operation for a detail endpoint

        Returns the response from NetBox for a detail endpoint.

        :args \**kwargs: key/value pairs that get converted into url
            parameters when passed to the endpoint.
            E.g. ``.list(method='get_facts')`` would be converted to
            ``.../?method=get_facts``.

        :returns: A dictionary or list of dictionaries its retrieved
            from NetBox.
        """
        if kwargs:
            self.request_kwargs['base'] = '{}{}'.format(
                self.url, url_param_builder(kwargs))

        return Request(**self.request_kwargs).get()
Example #12
0
    def update(self, *args, **kwargs):
        """Updates an object on an endpoint.

        :arg int,optional key: id for the item to be
            updated. Can

        :arg str,optional \**kwargs: Accepts the same keyword args as
            filter(). Any search argeter the endpoint accepts can
            be added as a keyword arg.

        :returns: A single updated object.

        :raises ValueError: If ID is not passed as a poitional arg, a value in a dict or as a kwarg

        :Examples:

        Update a device, given a device with ID of "10"

        If using positional args, ID must be first

        >>> nb.dcim.devices.update(10, {'name': 'mydevice'})
        mydevice
        >>>

        Using kwargs

        >>> nb.devices.update(id=10, name='mydevice')
        mydevice
        >>>

        Using a dict
        >>> nb.devices.update({'id': 10, 'name': 'mydevice'})
        mydevice
        >>>
        """
        key = None
        upd = None
        if len(args) == 1:
            if isinstance(args[0], dict):
                if 'id' in args[0]:
                    key = args[0].pop('id')
                    upd = args[0]
        elif len(args) > 1:
            try:
                key = int(args[0])
                upd = args[1]
            except ValueError:
                key = None
        elif 'id' in kwargs:
            key = kwargs.pop('id')
            upd = kwargs

        if not key:
            raise ValueError('No ID in provided args')

        if not upd:
            raise ValueError("No update data")

        return Request(key=key,
                       base=self.url,
                       token=self.token,
                       session_key=self.session_key,
                       version=self.version,
                       ssl_verify=self.ssl_verify).patch(upd)