blob: 23a108c0e708e4bff3a1914a78555681c09313a9 [file] [log] [blame]
Moshe0bb532c2018-02-26 13:39:57 +02001#!/usr/bin/env python
2##############################################################################
3# Copyright 2018 EuropeanSoftwareMarketingLtd.
4# ===================================================================
5# Licensed under the ApacheLicense, Version2.0 (the"License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# software distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and limitations under
13# the License
14##############################################################################
15
16import json
17import urllib2
18import requests
19
20
21def post(url, headers, data, logger):
22 return call(url, 'POST', headers, data, logger)
23
24
25def call(url, method, headers, data, logger):
26 data_json = json.dumps(data)
27 f = None
28 try:
29 req = urllib2.Request(url, data=data_json, headers=headers)
30 req.get_method = lambda: method
31 f = urllib2.urlopen(req)
32 return_code = f.code
33 response_body = f.read()
34 f.close()
35 if len(str(response_body)) == 0:
36 response_body = "{}"
37 response_body = json.loads(response_body)
38 result = {'return_code': return_code, 'body': response_body}
39 return result
40
41 except Exception as e:
42 message = "Cannot read content from {}, exception: {}".format(url, e)
43 logger.exception(message)
44 raise RuntimeError(message)
45 finally:
46 if f is not None:
47 f.close()
48
49
50def upload_file(url, headers, file, logger):
51 logger.debug("Upload file. URL: {}".format(url))
52 response = None
53 try:
54 response = requests.post(url, headers=headers, files=file)
55 return {'return_code': response.status_code, 'body': response.json()}
56 except Exception as e:
57 message = "Error while uploading file to {}, exception: {}".format(url, e)
58 logger.exception(message)
59 raise RuntimeError(message)
60 finally:
61 if response is not None:
62 response.close()