1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2011 Citrix Systems
6
# Licensed under the Apache License, Version 2.0 (the "License"); you may
7
# not use this file except in compliance with the License. You may obtain
8
# a copy of the License at
10
# http://www.apache.org/licenses/LICENSE-2.0
12
# Unless required by applicable law or agreed to in writing, software
13
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
# License for the specific language governing permissions and limitations
23
class MiniClient(object):
25
"""A base client class - derived from Glance.BaseClient"""
27
action_prefix = '/v0.1/tenants/{tenant_id}'
29
def __init__(self, host, port, use_ssl):
31
Creates a new client to some service.
33
:param host: The host where service resides
34
:param port: The port where service resides
35
:param use_ssl: Should we use HTTPS?
39
self.use_ssl = use_ssl
40
self.connection = None
42
def get_connection_type(self):
44
Returns the proper connection type
47
return httplib.HTTPSConnection
49
return httplib.HTTPConnection
51
def do_request(self, tenant, method, action, body=None,
52
headers=None, params=None):
54
Connects to the server and issues a request.
55
Returns the result data, or raises an appropriate exception if
56
HTTP status code is not 2xx
58
:param method: HTTP method ("GET", "POST", "PUT", etc...)
59
:param body: string of data to send, or None (default)
60
:param headers: mapping of key/value pairs to add as headers
61
:param params: dictionary of key/value pairs to add to append
65
action = MiniClient.action_prefix + action
66
action = action.replace('{tenant_id}', tenant)
67
if type(params) is dict:
68
action += '?' + urllib.urlencode(params)
71
connection_type = self.get_connection_type()
72
headers = headers or {}
74
# Open connection and send request
75
c = connection_type(self.host, self.port)
76
c.request(method, action, body, headers)
78
status_code = self.get_status_code(res)
79
if status_code in (httplib.OK,
85
raise Exception("Server returned error: %s" % res.read())
87
except (socket.error, IOError), e:
88
raise Exception("Unable to connect to "
89
"server. Got error: %s" % e)
91
def get_status_code(self, response):
93
Returns the integer status code from the response, which
94
can be either a Webob.Response (used in testing) or httplib.Response
96
if hasattr(response, 'status_int'):
97
return response.status_int
99
return response.status