1 # Copyright 2017 Sandvine
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
17 from io
import BytesIO
24 def __init__(self
, url
, user
="admin", password
="admin"):
27 self
._password
= password
28 self
._http
_header
= None
29 self
._logger
= logging
.getLogger("osmclient")
31 def set_http_header(self
, header
):
32 self
._http
_header
= header
34 def _get_curl_cmd(self
, endpoint
):
35 curl_cmd
= pycurl
.Curl()
36 curl_cmd
.setopt(pycurl
.URL
, self
._url
+ endpoint
)
37 curl_cmd
.setopt(pycurl
.SSL_VERIFYPEER
, 0)
38 curl_cmd
.setopt(pycurl
.SSL_VERIFYHOST
, 0)
39 curl_cmd
.setopt(pycurl
.USERPWD
, "{}:{}".format(self
._user
, self
._password
))
41 curl_cmd
.setopt(pycurl
.HTTPHEADER
, self
._http
_header
)
44 def get_cmd(self
, endpoint
):
46 curl_cmd
= self
._get
_curl
_cmd
(endpoint
)
47 curl_cmd
.setopt(pycurl
.HTTPGET
, 1)
48 curl_cmd
.setopt(pycurl
.WRITEFUNCTION
, data
.write
)
50 "Request METHOD: {} URL: {}".format("GET", self
._url
+ endpoint
)
53 http_code
= curl_cmd
.getinfo(pycurl
.HTTP_CODE
)
54 self
._logger
.info("Response HTTPCODE: {}".format(http_code
))
58 "Response DATA: {}".format(json
.loads(data
.getvalue().decode()))
60 return json
.loads(data
.getvalue().decode())
63 def delete_cmd(self
, endpoint
):
65 curl_cmd
= self
._get
_curl
_cmd
(endpoint
)
66 curl_cmd
.setopt(pycurl
.CUSTOMREQUEST
, "DELETE")
67 curl_cmd
.setopt(pycurl
.WRITEFUNCTION
, data
.write
)
69 "Request METHOD: {} URL: {}".format("DELETE", self
._url
+ endpoint
)
72 http_code
= curl_cmd
.getinfo(pycurl
.HTTP_CODE
)
73 self
._logger
.info("Response HTTPCODE: {}".format(http_code
))
77 "Response DATA: {}".format(json
.loads(data
.getvalue().decode()))
79 return json
.loads(data
.getvalue().decode())
89 curl_cmd
= self
._get
_curl
_cmd
(endpoint
)
90 curl_cmd
.setopt(pycurl
.POST
, 1)
91 curl_cmd
.setopt(pycurl
.WRITEFUNCTION
, data
.write
)
93 if postfields_dict
is not None:
94 jsondata
= json
.dumps(postfields_dict
)
95 curl_cmd
.setopt(pycurl
.POSTFIELDS
, jsondata
)
97 if formfile
is not None:
99 pycurl
.HTTPPOST
, [((formfile
[0], (pycurl
.FORM_FILE
, formfile
[1])))]
103 "Request METHOD: {} URL: {}".format("POST", self
._url
+ endpoint
)
106 http_code
= curl_cmd
.getinfo(pycurl
.HTTP_CODE
)
107 self
._logger
.info("Response HTTPCODE: {}".format(http_code
))
111 "Response DATA: {}".format(json
.loads(data
.getvalue().decode()))
113 return json
.loads(data
.getvalue().decode())