# Views

## Accessing objects

NDB objects are grouped into “views”:

> - interfaces

> - addresses

> - routes

> - neighbours

> - rules

> - netns

> - …

Views are dictionary-like objects that accept strings or dict selectors:

    # access eth0
    ndb.interfaces["eth0"]

    # access eth0 in the netns test01
    ndb.sources.add(netns="test01")
    ndb.interfaces[{"target": "test01", "ifname": "eth0"}]

    # access a route to 10.4.0.0/24
    ndb.routes["10.4.0.0/24"]

    # same with a dict selector
    ndb.routes[{"dst": "10.4.0.0", "dst_len": 24}]

## Objects cache

NDB create objects on demand, it doesn’t create thousands of route objects for thousands of routes by default. The object is being created only when accessed for the first time, and stays in the cache as long as it has any not committed changes. To inspect cached objects, use views’ .cache:

    >>> ndb.interfaces.cache.keys()
    [(('target', u'localhost'), ('tflags', 0), ('index', 1)),  # lo
     (('target', u'localhost'), ('tflags', 0), ('index', 5))]  # eth3

There is no asynchronous cache invalidation, the cache is being cleaned up every time when an object is accessed.

## API

class pyroute2.ndb.view.View

  The View() object returns RTNL objects on demand:

      ifobj1 = ndb.interfaces['eth0']
      ifobj2 = ndb.interfaces['eth0']
      # ifobj1 != ifobj2

  get(*argv, **kwarg)

    Return the value for key if key is in the dictionary, else default.

  locate(*argv, **kwarg)

    This method works like __getitem__(), but the important difference is that it uses only key fields to locate the object in the DB, ignoring all other keys.

    It is useful to locate objects that may change attributes during request, like an interface may come up/down, or an address may become primary/secondary, so plain __getitem__() will not match while the object still exists.

  exists(key, table=None)

    Check if the specified object exists in the database:

        ndb.interfaces.exists('eth0')
        ndb.interfaces.exists({'ifname': 'eth0', 'target': 'localhost'})
        ndb.addresses.exists('127.0.0.1/8')

  keys(*argv, **kwarg)

    Return a set-like object providing a view on the dict’s keys.

  values(*argv, **kwarg)

    Return an object providing a view on the dict’s values.

  items(*argv, **kwarg)

    Return a set-like object providing a view on the dict’s items.