Hints for Pynetbox

Note: I don’t yet have extensive experience on NetBox 2.9.x but these have been shown useful in earlier NetBox versions. I’ll update the page later if I find some further comments about the performance in NetBox 2.9.x.

Speeding up fetching the devices

Fetching lots of devices (hundreds or thousands, depending on the environment) with netbox.dcim.devices.all() can be slow. What I’m using nowadays instead is:

devices = netbox.dcim.devices.filter(exclude="config_context")

That’s a lot faster. Obviously the config contexts are not there then, but that is not usually problem in my usage.

Concurrency or threading

When fetching lots of objects there is threading available in recent pynetbox versions:

netbox = pynetbox.api(url, token, threading=True)

Threading means that instead of fetching the objects (with .all() or .filter()) serially in page-size chunks, pynetbox will determine the request page size and then issue the HTTP GET requests in parallel using several threads. Depending on the system and the size of the request the speedup can be noticeable.

However, due to a bug using threading is not reliable before pynetbox version 5.0.3. So, don’t use it if you have older pynetbox, you will get invalid results. It is a good idea to check the later versions as well because there are some other occasional fixes and improvements.

Using custom fields

When creating an object and populating the custom field, you do it with a dictionary like this:

device = netbox.dcim.devices.create(name="test", site_id=123, custom_fields={"field_name": "Field Contents"})

When filtering with a custom field, it’s like this:

devices = netbox.dcim.devices.filter(cf_field_name="Field Contents", exclude="config_context")

And, when referencing the field of a device object, you use dictionary syntax again:

print(device.custom_fields["field_name"])

2 Comments

Add a Comment

Leave a Reply