Timeout and Self-signed CA Handling in Pynetbox 5.x

Since pynetbox 5.0 it is possible to set the HTTP request connect timeout in your pynetbox.Api instance. Actually, it is not just a timeout value but you can instantiate a full requests.Session() object to customize the HTTP calls.

As a side effect, since the SSL/TLS certificate checking parameter can also be set in the session object, pynetbox chose to migrate away from the ssl_verify argument for pynetbox.Api. Thus you may need to use requests.Session() right away when using pynetbox 5.1.0 (the latest as of now). Here are some examples of using it.

First, if you only desire the functionality of the previous ssl_verify argument, this is what you need:

import pynetbox
import requests

netbox = pynetbox.api("https://my.server/", token="verysecret")
session = requests.Session()
session.verify = False
# Or set it to the location of your CA certificate file:
# session.verify = "/usr/local/share/ca-certificates/my-root.crt"
netbox.http_session = session
print(netbox.dcim.devices.all()) # Or whatever you do with it

Obviously that’s a bit different from pynetbox 4.x but that’s the way it is now.

The actual benefit of using the requests.Session() instance is to be able to configure other options as well, and the one mentioned in pynetbox documentation is the connect timeout value. By default the requests library does not set any timeout values, so if your NetBox server does not respond, your automation applications may hang waiting for response. Here is what you can do about it:

import pynetbox
import requests
from requests.adapters import HTTPAdapter

class TimeoutHTTPAdapter(HTTPAdapter):
    """ Adapter for setting pynetbox timeouts
    """
    def __init__(self, *args, **kwargs):
        self.timeout = 5 # Or whatever you want as default
        if "timeout" in kwargs:
            self.timeout = kwargs["timeout"]
            del kwargs["timeout"]
        super().__init__(*args, **kwargs)

    def send(self, request, **kwargs):
        if kwargs["timeout"] is None:
            kwargs["timeout"] = self.timeout
        return super().send(request, **kwargs)

netbox = pynetbox.api("https://my.server/", token="verysecret")
session = requests.Session()
session.verify = False # See the previous snippet
adapter = TimeoutHTTPAdapter()
session.mount("https://", adapter) # If using http, modify this
netbox.http_session = session

You can also use adapter = TimeoutHTTPAdapter(timeout=1) to override the default timeout, or you can just change the default value in the class definition if this is the only place where you use this code.

Leave a Reply