Skip to content

Commit 9c84bea

Browse files
author
SoftLayer
committed
Initial commit.
0 parents  commit 9c84bea

8 files changed

Lines changed: 986 additions & 0 deletions

File tree

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
.DS_Store
2+
*.swp
3+
Thumbs.db
4+
.svn
5+
._*
6+
*.pyc

LICENSE.textile

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Copyright (c) 2010, "SoftLayer Technologies, Inc.":http://www.softlayer.com/ All rights reserved.
2+
3+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4+
5+
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6+
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
7+
* Neither SoftLayer Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
8+
9+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10+
11+
This software is bundled with distribute_setup.py, a portion of the "Distribute":http://packages.python.org/distribute/ Python package.

README.textile

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
h1. A SoftLayer API Python client.
2+
3+
h2. Overview
4+
5+
SoftLayer.API.Client provides a simple method for connecting to and making calls from the SoftLayer XML-RPC API and provides support for many of the SoftLayer API's features. XML-RPC method calls and client management are handled by Python's built-in xmlrpc client class.
6+
7+
Currently the SoftLayer API only allows connections from within the SoftLayer private network. The system using this class must be either directly connected to the SoftLayer private network (eg. purchased from SoftLayer) or has access to the SoftLayer private network via a VPN connection.
8+
9+
Making API calls using the SoftLayer.API.Client class is done in the following steps:
10+
11+
# Instantiate a new SoftLayer.API.Client object. Provide the name of the service that you wish to query, an optional id number of the object that you wish to instantiate, your SoftLayer API username, and your SoftLayer API key.
12+
# Define and add optional headers to the client, such as object masks and result limits.
13+
# Call the API method you wish to call as if it were local to your client object. This class throws exceptions if it's unable to execute a query, so it's best to place API method calls in try / except statements for proper error handling.
14+
15+
Once your method is done executed you may continue using the same client if you need to conenct to the same service or define another client object if you wish to work with multiple services at once.
16+
17+
The most up to date version of this library can be found on the SoftLayer github public repositories: "http://github.com/softlayer/":http://github.com/softlayer/ . Please post to the SoftLayer forums <"http://forums.softlayer.com/":http://forums.softlayer.com/> or open a support ticket in the SoftLayer customer portal if you have any questions regarding use of this library.
18+
19+
h2. System Requirements
20+
21+
This library has been tested to work in Pyhton 2.4 - 3.1 on POSIX compliant and Windows operating systems.
22+
23+
A network connection is required for installation, and a connection to the SoftLayer private network and a valid SoftLayer API username and key are required to call the SoftLayer API.
24+
25+
h2. Installation
26+
27+
Change directory to your downloaded project root directory and run the following command to install this pagkage:
28+
29+
@python ./setup.py install@
30+
31+
Add @--help@ to the end of this command to view installation options.
32+
33+
h2. Usage
34+
35+
This installs the SoftLayer.API package into your Python installation's @site-packages@ directory. SoftLayer.API contains a Client class that handles API method calls per service.
36+
37+
These examples are written for Python 2.x. Python 3.x users will need to modify print() usage and change how exceptions are caught.
38+
39+
Here's a simple usage example that retrieves account information by calling the "getObject()":http://sldn.softlayer.com/wiki/index.php/SoftLayer_Account::getObject method in the "SoftLayer_Account":http://sldn.softlayer.com/wiki/index.php/SoftLayer_Account service:
40+
41+
<pre><code>
42+
import SoftLayer.API
43+
import pprint
44+
45+
api_username = 'set me'
46+
api_key = 'set me too'
47+
48+
client = SoftLayer.API.Client('SoftLayer_Account', None, api_username, api_key)
49+
50+
try:
51+
account = client.getObject()
52+
pprint.pprint(account)
53+
except Exception, e:
54+
print "Unable to retrieve account information: %", e
55+
</code></pre>
56+
57+
For a more complex example we'll retrieve a support ticket with id 123456 along with the ticket's updates, the user it's assigned to, the servers attached to it, and the datacenter those servers are in. We'll retrieve our extra information using a nested object mask. After we have the ticket we'll update it with the text 'Hello!'.
58+
59+
<pre><code>
60+
import SoftLayer.API
61+
62+
api_username = 'set me'
63+
api_key = 'set me too'
64+
65+
client = SoftLayer('SoftLayer_Ticket', 123456, api_username, api_key)
66+
67+
# Assign an object mask to our API client:
68+
client.set_object_mask({
69+
'updates' : {},
70+
'assignedUser' : {},
71+
'attachedHardware' : {
72+
'datacenter' : {}
73+
},
74+
})
75+
76+
try:
77+
ticket = client.getObject()
78+
except Exception, e:
79+
print "Unable to retrieve ticket record: %", e
80+
81+
# Update the ticket.
82+
update = {
83+
'entry' : 'Hello!',
84+
}
85+
86+
try:
87+
update = client.addUpdate(update)
88+
print "Update ticket 123456. The new update's id is %.", update{'id'}
89+
except Exception, e:
90+
print "Unable to update ticket: %", e
91+
</code></pre>
92+
93+
h2. Author
94+
95+
This software is written by the SoftLayer Development Team <"[email protected]":mailto:[email protected]>.
96+
97+
h2. Copyright
98+
99+
This software is Copyright (c) 2010 "SoftLayer Technologies, Inc":http://www.softlayer.com/. See the bundled LICENSE.textile file for more information.

SoftLayer/API.py

Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
# Copyright (c) 2010, SoftLayer Technologies, Inc. All rights reserved.
2+
#
3+
# Redistribution and use in source and binary forms, with or without
4+
# modification, are permitted provided that the following conditions are met:
5+
#
6+
# * Redistributions of source code must retain the above copyright notice,
7+
# this list of conditions and the following disclaimer.
8+
# * Redistributions in binary form must reproduce the above copyright notice,
9+
# this list of conditions and the following disclaimer in the documentation
10+
# and/or other materials provided with the distribution.
11+
# * Neither SoftLayer Technologies, Inc. nor the names of its contributors may
12+
# be used to endorse or promote products derived from this software without
13+
# specific prior written permission.
14+
#
15+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25+
# POSSIBILITY OF SUCH DAMAGE.
26+
27+
import xmlrpclib
28+
29+
"""
30+
@type API_USERNAME: C{str}
31+
@var API_USERNAME: Your API username, if you wish to hardcode all API calls to
32+
a single user.
33+
34+
@type API_KET: C{str}
35+
@var API_KEY: Your API key, if you wish to hardcode all API calls to a single
36+
user.
37+
38+
@type API_BASE_URL: C{str}
39+
@var API_BASE_URL: The base URL for the SoftLayer API's XML-RPC endpoints.
40+
"""
41+
42+
API_USERNAME = None
43+
API_KEY = None
44+
API_BASE_URL = 'http://api.service.softlayer.com/xmlrpc/v3/'
45+
46+
47+
class Client:
48+
"""
49+
A SoftLayer API client
50+
51+
Clients are intended to be declared once per service and used for all calls
52+
made to that service.
53+
54+
@ivar _service_name: The name of the SoftLayer API service to query
55+
@ivar _headers: The headers to send to an API call
56+
@ivar _client: The xmlrpc client used to make calls
57+
"""
58+
59+
_service_name = None
60+
_headers = {}
61+
_xmlrpc_client = None
62+
63+
def __init__(self, service_name, id=None, username=None, api_key=None):
64+
"""
65+
Create a SoftLayer API client
66+
67+
@type service_name: C{str}
68+
@param service:name: The name of the SoftLayer API service to query.
69+
70+
@type id: C{int}
71+
@param id: An optional object if if you're instantiating a particular
72+
SoftLayer_API object. Setting an id defines this client's
73+
initialization parameter.
74+
75+
@type username: C{str}
76+
@param username: An optional API username if you wish to bypass the
77+
package's built-in username.
78+
79+
@type api_key: C{str}
80+
@param api_key: An optional API key if you wish to bypass the package's
81+
built in API key.
82+
"""
83+
84+
service_name = service_name.strip()
85+
86+
if service_name is None or service_name is '':
87+
raise Exception('Please specify a service name.')
88+
89+
if username is None and API_USERNAME is None:
90+
raise Exception('Please provide a username.')
91+
92+
if api_key is None and API_KEY is None:
93+
raise Exception('Please provide an API key.')
94+
95+
# Assign local variables
96+
self._service_name = service_name
97+
98+
# Set authentication
99+
if API_USERNAME is None or API_USERNAME is '':
100+
user = username.strip()
101+
else:
102+
user = API_USERNAME.strip()
103+
104+
if API_KEY is None or API_KEY is '':
105+
key = api_key.strip()
106+
else:
107+
key = API_KEY.strip()
108+
109+
self.set_authentication(user,key)
110+
111+
# Set a call initialization parameter if we need to.
112+
if id is not None:
113+
self.set_init_parameter(int(id))
114+
115+
# Finally, make an xmlrpc client. We'll use this for all API calls made
116+
# against this client instance.
117+
self._xmlrpc_client = xmlrpclib.ServerProxy(API_BASE_URL
118+
+ self._service_name)
119+
def add_header(self, name, value):
120+
"""
121+
Set a SoftLayer API call header
122+
123+
Every header defines a customization specific to a SoftLayer API call.
124+
Most API calls require authentication and initialization parameter
125+
headers, but can also include optional headers such as object masks and
126+
result limits if they're supported by the API method you're calling.
127+
128+
@type name: C{str}
129+
@param name: The name of the header to add
130+
131+
@type value: C{dict}
132+
@param value: The header to add.
133+
"""
134+
name = name.strip()
135+
136+
if name is None or name is '':
137+
raise Exception('Please specify a header name.')
138+
139+
self._headers[name] = value
140+
141+
def remove_header(self, name):
142+
"""
143+
Remove a SoftLayer API call header
144+
145+
Removing headers may cause API queries to fail.
146+
147+
@type name: C{str}
148+
@param name: The name of the header to remove.
149+
"""
150+
151+
name = name.strip()
152+
153+
if name in self._headers:
154+
del self._headers[name]
155+
156+
def set_authentication(self, username, api_key):
157+
"""
158+
Set a user and key to authenticate a SoftLayer API call
159+
160+
Use this method if you wish to bypass the API_USER and API_KEY class
161+
constants and set custom authentication per API call.
162+
163+
See U{https://manage.softlayer.com/Administrative/apiKeychain} for more
164+
information.
165+
166+
@type username: C{str}
167+
@param username: The username to authenticate an API call.
168+
169+
@type api_key: C{str}
170+
@param api_key: The user's API key.
171+
"""
172+
173+
username = username.strip()
174+
api_key = api_key.strip()
175+
176+
self.add_header('authenticate', {
177+
'username' : username,
178+
'apiKey' : api_key,
179+
})
180+
181+
def set_init_parameter(self, id):
182+
"""
183+
Set an initialization parameter header on a SoftLayer API call
184+
185+
Initialization parameters instantiate a SoftLayer API service object to
186+
act upon during your API method call. For instance, if your account has
187+
a server with id number 1234, then setting an initialization parameter
188+
of 1234 in the SoftLayer_Hardware_Server Service instructs the API to
189+
act on server record 1234 in your method calls.
190+
191+
See U{http://sldn.softlayer.com/wiki/index.php/Using_Initialization_Parameters_in_the_SoftLayer_API}
192+
for more information.
193+
194+
@type id: C{int}
195+
@param id: The id number of the SoftLayer API object to instantiate
196+
"""
197+
198+
self.add_header(self._service_name + 'InitParameters', {
199+
'id': int(id)
200+
})
201+
202+
def set_object_mask(self, mask):
203+
"""
204+
Set an object mask to a SoftLayer API call
205+
206+
Use an object mask to retrieve data related your API call's result.
207+
Object masks are skeleton objects that define nested relational
208+
properties to retrieve along with an object's local properties. See
209+
U{http://sldn.softlayer.com/wiki/index.php/Using_Object_Masks_in_the_SoftLayer_API}
210+
for more information.
211+
212+
@type mask: C{dict}
213+
@param mask: The object mask you wish to define
214+
"""
215+
216+
if isinstance(mask, dict):
217+
self.add_header(self._service_name + 'ObjectMask', {
218+
'mask' : mask
219+
})
220+
221+
def set_result_limit(self, limit, offset=0):
222+
"""
223+
Set a result limit on a SoftLayer API call
224+
225+
Many SoftLayer API methods return a group of results. These methods
226+
support a way to limit the number of results retrieved from the
227+
SoftLayer API in a way akin to an SQL LIMIT statement.
228+
229+
@type limit: C{int}
230+
@param limit: The number of results to limit a SoftLayer API call to.
231+
232+
@type offset: C{int}
233+
@param offset: An optional offset to begin a SoftLayer API call's
234+
returned result at.
235+
"""
236+
237+
self.add_header('resultLimit', {
238+
'limit' : int(limit),
239+
'offset' : int(offset)
240+
})
241+
242+
def __getattr__(self, name):
243+
"""
244+
Attempt a SoftLayer API call
245+
246+
Use this as a catch-all so users can call SoftLayer API methods
247+
directly against their client object. If the property or method
248+
relating to their client object doesn't exist then assume the user is
249+
attempting a SoftLayer API call and return a simple function that makes
250+
an XML-RPC call.
251+
"""
252+
253+
try:
254+
return object.__getattr__(self, name)
255+
except AttributeError:
256+
def call_handler(*args, **kwargs):
257+
"""
258+
Place a SoftLayer API call
259+
"""
260+
261+
call_headers = {
262+
'headers': self._headers,
263+
}
264+
265+
try:
266+
return self._xmlrpc_client.__getattr__(name)(call_headers, *args)
267+
except xmlrpclib.Fault, e:
268+
raise Exception(e.faultString)
269+
270+
return call_handler

0 commit comments

Comments
 (0)