Skip to content

Commit ab902b0

Browse files
authored
Feature/get (#7)
* create project linting configuration * Defining `get_entity` method to search for entities. * Defining first exceptions for some cases.
1 parent addd859 commit ab902b0

File tree

7 files changed

+123
-88
lines changed

7 files changed

+123
-88
lines changed

.flake8

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
[flake8]
2+
ignore =
3+
F401,
4+
E501,
5+
exclude =
6+
.git,
7+
__pycache__,
8+
tests/fixtures/*,
9+
*.pyc,
10+
venv,
11+
deps =
12+
wheel,
13+
flake8-colors,
14+
max-complexity = 10
15+
import-order-style = google
16+
application-import-names = flake8
17+
format = ${cyan}%(path)s${reset}:${yellow_bold}%(row)d${reset}:${green_bold}%(col)d${reset}: ${red_bold}%(code)s${reset} %(text)s

pyhpipam/controller/__init__.py

Whitespace-only changes.

pyhpipam/controller/sections.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# -*- coding: utf-8 -*-
2+
# (c) Christian Meißner 2020

pyhpipam/core/api.py

Lines changed: 61 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
# -*- coding: utf-8 -*-
22
# (c) Christian Meißner 2020
33

4-
# pylint: disable=raise-missing-from
5-
# pylint: disable=super-with-arguments
6-
4+
import json
75
import requests
86

97
from requests.auth import HTTPBasicAuth
10-
from pyhpipam.core.query import query
8+
from pyhpipam.core.exceptions import PyHPIPAMException
119

1210
GET = requests.get
1311
POST = requests.post
@@ -48,11 +46,67 @@ def __init__(
4846
if not self._api_encryption:
4947
self._login()
5048

49+
def _query(self, **kwargs):
50+
""" sends queries to phpIPAM API in a generalistic manner
51+
52+
:param path: Path to the controler and possibly to function to use. Default is ```user```.
53+
:param method: method to be used for the query (choice: ```GET```, ```POST```, ```PATCH```, ```OPTIONS```).
54+
:param headers: Headers for request.
55+
:param data: (optional) Dictionary Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`.
56+
:param params: (optional) Dictionary list of tuples or bytes to send in the query string for the :class:`Request`.
57+
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
58+
:param token: (optional) Api token get from last login.
59+
"""
60+
61+
_api_path = kwargs.pop('path', 'user')
62+
_api_headers = kwargs.pop('headers', {})
63+
_method = kwargs.pop('method', 'GET')
64+
_data = kwargs.pop('data', None)
65+
_params = kwargs.pop('params', {})
66+
_auth = kwargs.pop('auth', None)
67+
68+
if self._api_token:
69+
_api_headers['token'] = self._api_token
70+
71+
_url = '{}/api/{}/{}'.format(self._api_url, self._api_appid, _api_path)
72+
73+
if _data is not None:
74+
_data = json.dumps(_data)
75+
76+
resp = _method(
77+
_url,
78+
params=_params,
79+
data=_data,
80+
headers=_api_headers,
81+
auth=_auth,
82+
verify=self._api_ssl_verify,
83+
timeout=self._api_timeout,
84+
)
85+
86+
result = resp.json()
87+
88+
if result['code'] not in (200, 201) or not result['success']:
89+
raise PyHPIPAMException(code=result['code'], message=result['message'])
90+
else:
91+
if 'data' in result:
92+
return result['data']
93+
5194
def _login(self):
5295
_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)
96+
resp = self._query(method=POST, auth=_auth)
5497

55-
self._token = resp['token']
98+
self._api_token = resp['token']
5699

57100
def get_token(self):
58-
return self._token
101+
return self._api_token
102+
103+
def get_entity(self, **kwargs):
104+
_controller = kwargs.pop('controller', None)
105+
_controller_path = kwargs.pop('controller_path', None)
106+
107+
if _controller_path is None and _controller:
108+
_path = '{}'.format(_controller)
109+
elif _controller and _controller_path:
110+
_path = '{}/{}'.format(_controller, _controller_path)
111+
112+
return self._query(token=self._api_token, method=GET, path=_path)

pyhpipam/core/exceptions.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# provides the main query methods.
2+
3+
import json
4+
5+
6+
class PyHPIPAMException(Exception):
7+
8+
def __init__(self, *args, **kwargs):
9+
self._code = kwargs.pop('code', None)
10+
self._message = kwargs.pop('message', None)
11+
12+
if self._code == 500:
13+
if self._message == 'Invalid username or password':
14+
raise PyHPIPAMInvalidCredentials(self._message)
15+
elif self._code == 400:
16+
raise PyHPIPAMInvalidSyntax(message=self._message)
17+
elif self._code == 404:
18+
if self._message == 'Not Found':
19+
raise EntityNotFoundException(self._message)
20+
21+
# super(PyHPIPAMException, self).__init__(*args, **kwargs)
22+
23+
24+
class PyHPIPAMInvalidCredentials(Exception):
25+
def __init__(self, *args, **kwargs):
26+
super(PyHPIPAMInvalidCredentials, self).__init__(*args, **kwargs)
27+
28+
29+
class EntityNotFoundException(Exception):
30+
def __init__(self, *args, **kwargs):
31+
super(EntityNotFoundException, self).__init__(*args, **kwargs)
32+
33+
34+
class PyHPIPAMInvalidSyntax(Exception):
35+
def __init__(self, *args, **kwargs):
36+
self._message = kwargs.pop('message', '')
37+
38+
super(PyHPIPAMInvalidSyntax, self).__init__(self._message, *args, **kwargs)

pyhpipam/core/query.py

Lines changed: 0 additions & 81 deletions
This file was deleted.

requirements-dev.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
wheel
2+
flake8
3+
flake8-colors
4+
requests
5+
inflection

0 commit comments

Comments
 (0)