-
Hey all, I'd like to start by saying I'd rather be taught how to teach myself the answer to these things but to keep to the point the situation is as so: I'm developing a custom script that connects to LibreNMS (an SNMP monitoring system) and will update a given device with the SNMP information found. My script at the moment is as so:
But what happens when I run the script is I get the following exception:
The error on my end occurs with the line: Like said at the beginning, I'd rather be taught how to teach myself but as far as I can tell, the documentation doesn't explain the inner workings of how the Netbox Python code handles certain transactions, so I have no easy reference to follow. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
See https://docs.djangoproject.com/en/3.2/topics/db/transactions/ at the section headed "Avoid catching exceptions inside atomic!" You are intentionally causing an IntegrityError with your failure to create a duplicate object, but this breaks the transaction in the database. Even though you catch the exception, the database layer has left the transaction in a broken state. The solution suggested is to wrap that bit of code in
|
Beta Was this translation helpful? Give feedback.
-
To answer my own question, I have discovered a few ways to go about it. As Candlerb shows in great detail above, using Next I started looking around for people's existing scripts and found one by Barbarossa. Inside you can see they write methods to both check if an attribute already exists within Netbox, and methods to update a given item with said attribute. The method I've decided to go down is to instead use the very well documented API that Netbox provides. Although it seems a bit redundant making a HTTP request to yourself, creating an authorization token for it, it means you don't have to try and figure out how all the code works as the API handles it for you. I hope the information shown here helps anybody else in the future. |
Beta Was this translation helpful? Give feedback.
To answer my own question, I have discovered a few ways to go about it.
As Candlerb shows in great detail above, using
transaction.atomic
to wrap around the saving transactions can help prevent failures, but my testing found it cannot be used as an absolute solution; In my case it only allowed me to carry on one more save before having no effect (but as you can see from above, I'm probably still not understanding all it properly, so that's on me not working with Netbox scripts before :) ).Next I started looking around for people's existing scripts and found one by Barbarossa. Inside you can see they write methods to both check if an attribute already exists within Netbox, and methods to …