RAPP Platform API
 All Classes Namespaces Files Functions Variables Typedefs
ServiceControllerBase.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 
5 # Copyright 2015 RAPP
6 
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 
11  #http://www.apache.org/licenses/LICENSE-2.0
12 
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 
19 # Authors: Konstantinos Panayiotou, Manos Tsardoulias
20 # contact: klpanagi@gmail.com, etsardou@iti.gr
21 
22 
23 ## @file ServiceController/ServiceControllerBase.py
24 #
25 # @copyright Rapp Projecty EU 2015
26 # @author Konstantinos Panayiotou, [klpanagi@gmail.com]
27 #
28 
29 
30 import json
31 from os import path
32 import sys
33 
34 import requests
35 from requests.auth import HTTPBasicAuth # Http basic authentication
36 from requests.exceptions import * # Requests Exceptions
37 
38 from RAPPAuth import RAPPAuth
39 from requests.adapters import HTTPAdapter
40 from Adapters import TLSAdapter as SSLAdapter
41 
42 
43 
44 class ServiceControllerBase(object):
45  """ Service Controller base class implementation """
46 
47  def __init__(self, service):
48  """! Constructor
49 
50  @param service Service: Service instance
51  @param connection dictionary: Connection information.
52  @param timeout int: Connection Timeout value.
53  """
54  ## Cloud Service instance.
55  self._service = service
56 
57  if self._service.persistent:
58  # Hold a session for keep-alive connections.
59  self.session_ = requests.Session()
60  self.__mount_adapters(self.session_)
61 
62  self.__auth = RAPPAuth()
63 
64  self.__customHeaders = {
65  'user-agent': 'rapp-platform-api/python'
66  }
67 
68 
69 
70  def is_json(self, obj):
71  """! Check if it is a json string.
72 
73  @param obj string
74  @return - True if is a json. False otherwise.
75  """
76  try:
77  json.loads(obj)
78  except ValueError:
79  return False
80  return True
81 
82 
83  def run_job(self):
84  raise NotImplementedError()
85 
86 
87  def basename(self, filepath):
88  """! Return the basename of input filepath. """
89  return path.basename(filepath)
90 
91 
92 
93  def post_request(self, session, url, payload={}, files=[]):
94  """! General member method to perform a .post request to the
95 
96  Platform service.
97  If files are specified, then multipart/form-data form is used.
98  Otherwhise, x-www-urlencoded form is used.
99 
100  @param session The session oject to use for this request.
101  @param urlpath The complete urlpath of the request.
102  @param data The data to send. Literal.
103  @param files Files to send.
104 
105  @return dictionary - Platform Service response.
106  """
107 
108  _payload = {'json': payload.make_json()}
109  _files = []
110  for f in files:
111  _files.append(f.make_tuple())
112 
113  response = {'error': ''}
114 
115  try:
116  resp = session.post(
117  url=url,
118  data=_payload,
119  files=_files,
120  headers=self.__customHeaders,
121  timeout=self._service.timeout,
122  verify=False,
123  auth=self.__auth)
124 
125  header = resp.headers
126  # Raise Exception for response status code.
127  resp.raise_for_status()
128  except Exception as e:
129  errorMsg = self.handle_exception(e)
130  response = {
131  'error': errorMsg
132  }
133  else:
134  # If response Content-Type is set to application/json.
135  if "application/json" in resp.headers['content-type']:
136  response = json.loads(resp.content)
137  elif "This service is unknown!" in resp.content:
138  response = {
139  'error': 'Connection Error. Connection could not be established at %s' %self._service.url
140  }
141  else:
142  # Uknown for the API response.
143  response = {
144  'payload': resp.content,
145  'error': 'Non application/json response'
146  }
147 
148  return response
149 
150 
151  def _post_session_once(self, url, data, files):
152  """! Post Request while initiating a new session
153 
154  @param data dictionary - the data payload to send.
155  @param files Array - Array of serialized File objects to send.
156  """
157  with requests.Session() as session:
158  self.__mount_adapters(self.session_)
159  resp = self.post_request(session, url, data, files)
160  return resp
161 
162 
163  def _post_persistent(self, url, data, files):
164  """! Post Request using active session - persistent connection.
165 
166  @param data dictionary - the data payload to send.
167  @param files Array - Array of serialized File objects to send.
168  """
169  return self.post_request(self.session_, url, data, files)
170 
171 
172  def __mount_adapters(self, session):
173  """! Mount http and https Transport Adapters to the session
174 
175  @param session Session - The session to mount the adapters.
176  """
177  session.mount("http://", HTTPAdapter())
178  session.mount("https://", SSLAdapter())
179 
180 
181  def handle_exception(self, exc):
182  """! Handles exceptions and return an error message that complies to
183  the Exception caught.
184 
185  @param exc Exception of any type
186  """
187 
188  print exc
189  errorMsg = ''
190  if type(exc) is ConnectionError:
191  errorMsg = "Connection Error"
192  elif "401" in str(exc):
193  # Unauthorized 401 HTTP Error
194  errorMsg = str(exc)
195  elif "500" in str(exc):
196  # Internal Server Error
197  errorMsg = str(exc)
198  elif "404" in str(exc):
199  # Client Error. Requested url does not exist!
200  errorMsg = str(exc)
201  elif type(exc) is HTTPError:
202  errorMsg = str(exc)
203  elif type(exc) is ConnectTimeout:
204  errorMsg = "The request timed out while trying to connect to the remote server"
205  elif type(exc) is ReadTimeout:
206  errorMsg = "The server did not send any data in the allotted amount of time."
207  elif type(exc) is Timeout:
208  errorMsg = "Connection Timeout exception."
209  else:
210  errorMsg = "Catched Exception %s" %exc
211 
212  return errorMsg
def _post_persistent
Post Request using active session - persistent connection.
def handle_exception
Handles exceptions and return an error message that complies to the Exception caught.
def __mount_adapters
Mount http and https Transport Adapters to the session.
def _post_session_once
Post Request while initiating a new session.
def post_request
General member method to perform a .post request to the.