Commit ba3e7846 authored by Morten Brekkevold's avatar Morten Brekkevold

Refactor to use simple_rest_client for API access.

parent 8931d6ed
......@@ -17,7 +17,7 @@ import argparse
from slack_log_handler import SlackLogHandler
from kindnavsync.navapi import NAVAPI, ObjectNotFound
from kindnavsync.navapi import NAVAPI, ObjectNotFound, ClientError
KIND_SERVICE_URL = "https://kind.uninett.no/autoregister/utstyr_eksport.json"
KIND_UTSTYR_URL = "https://kind.uninett.no/utstyr/edit_utstyr.html?id={id}"
......@@ -424,16 +424,22 @@ def insert_one_into_nav(nav_api, kind_device):
room = dict(id=kind_device.room, location=DEFAULT_LOCATION)
try:
nav_api.post_room(room)
except requests.HTTPError as error:
LOG.error("Room post feilet for %s. Feilrespons: %s",
kind_device.room, error.response.content.decode())
except ClientError as error:
LOG.error(
"Room post feilet for %s. Feilrespons: %s",
kind_device.room,
error,
)
raise
try:
nav_api.post_netbox(netbox)
except requests.HTTPError as error:
LOG.error("Netbox post feilet for %s. Feilrespons: %s",
netbox.get('sysname'), error.response.content.decode())
except ClientError as error:
LOG.error(
"Netbox post feilet for %s. Feilrespons: %s",
netbox.get('sysname'),
error,
)
raise
......
"""Very simple interface against the NAV API"""
import requests
from requests.exceptions import HTTPError
import functools
from simple_rest_client.api import API
from simple_rest_client.exceptions import NotFoundError, ClientError
class NAVAPI(object):
def __init__(self, url, auth_token):
self.url = url
self.auth_token = auth_token
def _endpoint(self, name):
return self.url + name
def _translate_notfounderror(func):
"""Decorator for standardized handling of NotFoundError"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except NotFoundError as error:
raise ObjectNotFound(error.response.body)
def _base_headers(self):
return {'Authorization': 'Token {}'.format(self.auth_token)}
return wrapper
def _simple_get(self, endpoint, **kwargs):
response = requests.get(
self._endpoint(endpoint),
headers=self._base_headers(),
**kwargs
)
response.raise_for_status()
return response.json()
def _simple_post(self, endpoint, data, **kwargs):
response = requests.post(
self._endpoint(endpoint),
headers=self._base_headers(),
data=data,
**kwargs
)
response.raise_for_status()
return response.json()
def _simple_patch(self, endpoint, data, **kwargs):
response = requests.patch(
self._endpoint(endpoint),
headers=self._base_headers(),
data=data,
**kwargs
)
response.raise_for_status()
return response.json()
def _simple_delete(self, endpoint, **kwargs):
response = requests.delete(
self._endpoint(endpoint),
headers=self._base_headers(),
**kwargs
class NAVAPI(object):
def __init__(self, url, auth_token):
self.api = API(
url,
headers={
'Authorization': 'Token {}'.format(auth_token),
'Content-Type': 'application/json',
},
append_slash=True,
json_encode_body=True,
)
response.raise_for_status()
return response
self.api.add_resource(resource_name='netbox')
self.api.add_resource(resource_name='room')
def list_netboxes(self):
response = self._simple_get('/netbox?page_size=1000')
return response['results']
response = self.api.netbox.list(params={'page_size': 1000})
return response.body['results']
@_translate_notfounderror
def get_netbox(self, netbox_id):
try:
response = self._simple_get('/netbox/{}/'.format(netbox_id))
except HTTPError as error:
if error.response.status_code == 404:
raise ObjectNotFound(error.response.content.decode())
else:
raise
return response
return self.api.netbox.retrieve(netbox_id)
def post_netbox(self, netbox):
response = self._simple_post('/netbox/', data=netbox)
return response
return self.api.netbox.create(body=netbox)
@_translate_notfounderror
def patch_netbox(self, netbox_id, patch):
try:
response = self._simple_patch('/netbox/{}/'.format(netbox_id),
data=patch)
except HTTPError as error:
if error.response.status_code == 404:
raise ObjectNotFound(error.response.content.decode())
else:
raise
return response
return self.api.netbox.partial_update(netbox_id, body=patch)
def delete_netbox(self, netbox_id):
response = self._simple_delete("/netbox/{}/".format(netbox_id))
return response
return self.api.netbox.destroy(netbox_id)
@_translate_notfounderror
def get_room(self, room_id):
try:
response = self._simple_get('/room/{}/'.format(room_id))
except HTTPError as error:
if error.response.status_code == 404:
raise ObjectNotFound(error.response.content.decode())
else:
raise
return response
return self.api.room.retrieve(room_id)
def post_room(self, room):
response = self._simple_post('/room/', data=room)
return response
return self.api.room.create(body=room)
# Exception classes
......
......@@ -3,7 +3,7 @@ from setuptools import setup
setup(
name="kindnavsync",
version="0.2.10",
version="0.3.0",
author="Morten Brekkevold",
author_email="morten.brekkevold@uninett.no",
description="Synchronizes device information from Kind to NAV",
......@@ -14,6 +14,7 @@ setup(
packages=['kindnavsync'],
install_requires=[
'requests',
'simple_rest_client',
'slack_log_handler',
],
python_requires='>3.4.0',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment