Skip to content

Commit 047f87f

Browse files
committed
Add basic functionality
* add base query method * finalize Api class * add login method
1 parent 7151982 commit 047f87f

File tree

4 files changed

+139
-2
lines changed

4 files changed

+139
-2
lines changed

pyhpipam/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from pkg_resources import get_distribution, DistributionNotFound
22

3-
from pyhpipam.core.query import RequestError, AllocationError, ContentError
43
from pyhpipam.core.api import Api as api
54

5+
66
try:
77
__version__ = get_distribution(__name__).version
88
except DistributionNotFound:

pyhpipam/core/api.py

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,58 @@
1-
# provides a common api object to work on.
1+
# -*- coding: utf-8 -*-
2+
# (c) Christian Meißner 2020
3+
4+
# pylint: disable=raise-missing-from
5+
# pylint: disable=super-with-arguments
6+
7+
import requests
8+
9+
from requests.auth import HTTPBasicAuth
10+
from pyhpipam.core.query import query
11+
12+
GET = requests.get
13+
POST = requests.post
14+
PATCH = requests.patch
15+
OPTIONS = requests.options
16+
17+
18+
class Api(object):
19+
20+
def __init__(
21+
self,
22+
url,
23+
app_id,
24+
username=None,
25+
password=None,
26+
token=None,
27+
encryption=False,
28+
timeout=None,
29+
ssl_verify=True,
30+
user_agent=None
31+
):
32+
self._api_url = url
33+
self._api_appid = app_id
34+
self._api_username = username
35+
self._api_password = password
36+
self._api_token = token
37+
self._api_encryption = encryption
38+
self._api_timeout = timeout
39+
self._api_ssl_verify = ssl_verify
40+
41+
self._api_headers = {
42+
'content-type': 'application/json',
43+
}
44+
45+
if user_agent:
46+
self._api_headers['user-agent'] = user_agent
47+
48+
if not self._api_encryption:
49+
self._login()
50+
51+
def _login(self):
52+
_auth = HTTPBasicAuth(self._api_username, self._api_password)
53+
resp = query(url=self._api_url, app_id=self._api_appid, method=POST, auth=_auth, verify=self._api_ssl_verify)
54+
55+
self._token = resp['token']
56+
57+
def get_token(self):
58+
return self._token

pyhpipam/core/query.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,81 @@
11
# provides the main query methods.
2+
3+
import json
4+
5+
6+
class InvalidUsernameOrPasswordException(Exception):
7+
def __init__(self, *args, **kwargs):
8+
super(InvalidUsernameOrPasswordException, self).__init__(*args, **kwargs)
9+
10+
11+
class EntityNotFoundException(Exception):
12+
def __init__(self, *args, **kwargs):
13+
super(EntityNotFoundException, self).__init__(*args, **kwargs)
14+
15+
16+
class ParameterNotDefinedException(Exception):
17+
def __init__(self, *args, **kwargs):
18+
super(ParameterNotDefinedException, self).__init__(*args, **kwargs)
19+
20+
21+
def query(**kwargs):
22+
""" sends queries to phpIPAM API in a generalistic manner
23+
24+
:param url: URL to the api of the phpIPAM instace. Needs to include the used scheme like ```https://``` or ```http://```.
25+
:param path: Path to the controler and possibly to function to use. Default is ```user```.
26+
:param app_id: Name of the app id used for this request.
27+
:param method: method to be used for the query (choice: ```GET```, ```POST```, ```PATCH```, ```OPTIONS```).
28+
:param headers: Headers for request.
29+
:param timeout: Timeout for request.
30+
:param verify: Should ssl certificate be verified. Default ```False```.
31+
:param data: (optional) Dictionary Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`.
32+
:param params: (optional) Dictionary list of tuples or bytes to send in the query string for the :class:`Request`.
33+
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
34+
:param token: (optional) Api token get from last login.
35+
"""
36+
37+
_api_url = kwargs.pop('url', None)
38+
_api_path = kwargs.pop('path', 'user')
39+
_api_appid = kwargs.pop('app_id', None)
40+
_api_headers = kwargs.pop('headers', {})
41+
_method = kwargs.pop('method', 'GET')
42+
_data = kwargs.pop('data', None)
43+
_params = kwargs.pop('params', {})
44+
_auth = kwargs.pop('auth', None)
45+
_api_token = kwargs.pop('token', None)
46+
_api_timeout = kwargs.pop('timeout', None)
47+
_api_ssl_verify = kwargs.pop('verify', False)
48+
49+
if _api_url is None:
50+
raise ParameterNotDefinedException('Parameter `url` not defined.')
51+
52+
if _api_appid is None:
53+
raise ParameterNotDefinedException('Parameter `app_id` not defined.')
54+
55+
if _api_token:
56+
_api_headers['token'] = _api_token
57+
58+
_url = '{}/api/{}/{}'.format(_api_url, _api_appid, _api_path)
59+
60+
if _data is not None:
61+
_data = json.dumps(_data)
62+
63+
resp = _method(
64+
_url,
65+
params=_params,
66+
data=_data,
67+
headers=_api_headers,
68+
auth=_auth,
69+
verify=_api_ssl_verify,
70+
timeout=_api_timeout,
71+
)
72+
73+
result = resp.json()
74+
75+
if result['code'] not in (200, 201) or not result['success']:
76+
if result['code'] == 500:
77+
if result['message'] == 'Invalid username or password':
78+
raise InvalidUsernameOrPasswordException(result['message'])
79+
else:
80+
if 'data' in result:
81+
return result['data']

0 commit comments

Comments
 (0)