TypeError: Can't convert 'int' object to str implicitly Python3.5.2 on Ubuntu 16.04 Server

Question:

I’m new to Python. I have some error right after I added

device_purpose = device["purpose"].rstrip()

I’ve tried to find the solution, but I still don’t get it.

[Line 118]

for alert in alerts["alerts"]:
    alert_rule = librenms_api.get_alert_rule(alert["rule_id"])
    device = librenms_api.get_device(alert["device_id"])
    device_status = device["status"]
    device_status_reason = device["status_reason"]
    device_hostname = librenms_api.translate_device_ip_to_sysname(device)
    device_location = re.sub(r'[.*]', '', device["location"]) # remove gp$
    alert_severity = alert["severity"]

[Line 61]

 def get_alert_rule(self,rule_id):
            rule_req = urllib.Request(self.api_url + "rules/" + rule_id, he$
            rule_contents = urllib.urlopen(rule_req).read()
            return json.loads(rule_contents)["rules"][0]

An error:

Traceback (most recent call last):
File "./open_alerts.py", line 118, in <module>
alert_rule = librenms_api.get_alert_rule(alert["rule_id"])
File "./open_alerts.py", line 61, in get_alert_rule
rule_req = urllib.Request(self.api_url + "rules/" + rule_id, headers=self.request_headers)
TypeError: Can't convert 'int' object to str implicitly

This is from git clone https://github.com/RaymiiOrg/librenms-api-alerts

Can you help me? Thank you.

Answers:

If rule_id is an int then you should cast to string:

str(rule_id)

Changing:

rule_req = urllib.Request(self.api_url + "rules/" + rule_id, headers=self.request_headers)

to

rule_req = urllib.Request(self.api_url + "rules/" + str(rule_id), headers=self.request_headers)
Answered By: Leonardo Mariga

I’m assuming rule_id has int value. Try converting it to string.

rule_req = urllib.Request(self.api_url + "rules/" + str(rule_id), headers=self.request_headers)

Answered By: suitsense
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.