restructure osmclient
[osm/osmclient.git] / osmclient / common / http.py
1 # Copyright 2017 Sandvine
2 #
3 # All Rights Reserved.
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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
15 # under the License.
16
17 from io import BytesIO
18 import pycurl
19 import json
20
21
22 class Http(object):
23
24 def __init__(self,url,user='admin',password='admin'):
25 self._url = url
26 self._user = user
27 self._password = password
28 self._http_header = None
29
30 def set_http_header(self,header):
31 self._http_header = header
32
33 def _get_curl_cmd(self,endpoint):
34 curl_cmd = pycurl.Curl()
35 curl_cmd.setopt(pycurl.URL, self._url + endpoint )
36 curl_cmd.setopt(pycurl.SSL_VERIFYPEER,0)
37 curl_cmd.setopt(pycurl.SSL_VERIFYHOST,0)
38 curl_cmd.setopt(pycurl.USERPWD, '{}:{}'.format(self._user,self._password))
39 if self._http_header:
40 curl_cmd.setopt(pycurl.HTTPHEADER, self._http_header)
41 return curl_cmd
42
43 def get_cmd( self, endpoint ):
44
45 data = BytesIO()
46 curl_cmd=self._get_curl_cmd(endpoint)
47 curl_cmd.setopt(pycurl.HTTPGET,1)
48 curl_cmd.setopt(pycurl.WRITEFUNCTION, data.write)
49 curl_cmd.perform()
50 curl_cmd.close()
51 if data.getvalue():
52 return json.loads(data.getvalue().decode())
53 return None
54
55 def delete_cmd( self, endpoint ):
56 data = BytesIO()
57 curl_cmd=self._get_curl_cmd(endpoint)
58 curl_cmd.setopt(pycurl.CUSTOMREQUEST, "DELETE")
59 curl_cmd.setopt(pycurl.WRITEFUNCTION, data.write)
60 curl_cmd.perform()
61 curl_cmd.close()
62 if data.getvalue():
63 return json.loads(data.getvalue().decode())
64 return None
65
66 def post_cmd( self, endpoint='', postfields_dict=None, formfile=None, ):
67 data = BytesIO()
68 curl_cmd=self._get_curl_cmd(endpoint)
69 curl_cmd.setopt(pycurl.POST,1)
70 curl_cmd.setopt(pycurl.WRITEFUNCTION, data.write)
71
72 if postfields_dict is not None:
73 jsondata=json.dumps(postfields_dict)
74 curl_cmd.setopt(pycurl.POSTFIELDS,jsondata)
75
76 if formfile is not None:
77 curl_cmd.setopt(pycurl.HTTPPOST,[((formfile[0],(pycurl.FORM_FILE,formfile[1])))])
78
79 curl_cmd.perform()
80 curl_cmd.close()
81 if data.getvalue():
82 return json.loads(data.getvalue().decode())
83 return None