Browse files

Adds Sphinx Documentation

* Adds documentation for Client and managers. The CLI code isn't covered yet.
* Consolidated iter logic into Client.call instead of Client.__call__.
  It's much easier to document that way.
* Added iter_call to SoftLayer.Service
* Added some missing doc blocks and fixed some incorrectly formatted blocks.
* Adds fabric script to build docs and push them up to github via gh-pages.
  Viewable here: http://softlayer.github.com/softlayer-api-python-client.
  • Loading branch information...
1 parent 8278e19 commit 81c0da8795fc9764826aed99b1b0b4abd58b3c68 @sudorandom committed Mar 24, 2013
View
1 .gitignore
@@ -7,6 +7,7 @@ Thumbs.db
.coverage
cover/*
.tox
+docs/_build/*
build/*
dist/*
*.egg-info
View
59 SoftLayer/API.py
@@ -5,8 +5,6 @@
:copyright: (c) 2013, SoftLayer Technologies, Inc. All rights reserved.
:license: BSD, see LICENSE for more details.
- :website: http://sldn.softlayer.com/article/Python
-
"""
from SoftLayer.consts import API_PUBLIC_ENDPOINT, API_PRIVATE_ENDPOINT, \
USER_AGENT
@@ -109,7 +107,7 @@ def set_authentication(self, username, api_key):
Use this method if you wish to bypass the API_USER and API_KEY class
constants and set custom authentication per API call.
- See U{https://manage.softlayer.com/Administrative/apiKeychain} for more
+ See https://manage.softlayer.com/Administrative/apiKeychain for more
information.
:param username: the username to authenticate with
@@ -132,7 +130,7 @@ def set_init_parameter(self, id):
of 1234 in the SoftLayer_Hardware_Server Service instructs the API to
act on server record 1234 in your method calls.
- See U{http://sldn.softlayer.com/article/Using-Initialization-Parameters-SoftLayer-API} # NOQA
+ See http://sldn.softlayer.com/article/Using-Initialization-Parameters-SoftLayer-API # NOQA
for more information.
:param id: the ID of the SoftLayer API object to instantiate
@@ -151,7 +149,7 @@ def set_object_mask(self, mask):
Object masks are skeleton objects, or strings that define nested
relational properties to retrieve along with an object's local
properties. See
- U{http://sldn.softlayer.com/article/Using-Object-Masks-SoftLayer-API}
+ http://sldn.softlayer.com/article/Using-Object-Masks-SoftLayer-API
for more information.
:param mask: the object mask you wish to define
@@ -200,15 +198,12 @@ def __call__(self, *args, **kwargs):
:param service: the name of the SoftLayer API service
:param method: the method to call on the service
- :param *args: same optional arguments that ``Client.call`` takes
- :param **kwargs: same optional keyword arguments that ``Client.call``
- takes
+ :param \*args: same optional arguments that ``Client.call`` takes
+ :param \*\*kwargs: same optional keyword arguments that ``Client.call``
+ takes
"""
- if kwargs.get('iter'):
- return self.iter_call(*args, **kwargs)
- else:
- return self.call(*args, **kwargs)
+ return self.call(*args, **kwargs)
def call(self, service, method, *args, **kwargs):
""" Make a SoftLayer API call
@@ -223,12 +218,17 @@ def call(self, service, method, *args, **kwargs):
:param dict raw_headers: (optional) HTTP transport headers
:param int limit: (optional) return at most this many results
:param int offset: (optional) offset results by this many
+ :param boolean iter: (optional) if True, returns a generator with the
+ results
Usage:
>>> client['Account'].getVirtualGuests(mask="id", limit=10)
[...]
"""
+ if kwargs.get('iter'):
+ return self.iter_call(service, method, *args, **kwargs)
+
objectid = kwargs.get('id')
objectmask = kwargs.get('mask')
objectfilter = kwargs.get('filter')
@@ -276,13 +276,24 @@ def call(self, service, method, *args, **kwargs):
def iter_call(self, service, method,
chunk=100, limit=None, offset=0, *args, **kwargs):
+ """ A generator that deals with paginating through results.
+
+ :param service: the name of the SoftLayer API service
+ :param method: the method to call on the service
+ :param integer chunk: result size for each API call
+ :param \*args: same optional arguments that ``Client.call`` takes
+ :param \*\*kwargs: same optional keyword arguments that ``Client.call``
+ takes
+
+ """
if chunk <= 0:
raise AttributeError("Chunk size should be greater than zero.")
if limit:
chunk = min(chunk, limit)
result_count = 0
+ kwargs['iter'] = False
while True:
if limit:
# We've reached the end of the results
@@ -361,7 +372,7 @@ def call_handler(*args, **kwargs):
raise SoftLayerError(
"Service is not set on Client instance.")
kwargs['headers'] = self._headers
- return self(self._service_name, name, *args, **kwargs)
+ return self.call(self._service_name, name, *args, **kwargs)
return call_handler
def __repr__(self):
@@ -389,7 +400,27 @@ def call(self, name, *args, **kwargs):
[...]
"""
- return self.client(self.name, name, *args, **kwargs)
+ return self.client.call(self.name, name, *args, **kwargs)
+
+ def iter_call(self, name, *args, **kwargs):
+ """ A generator that deals with paginating through results.
+
+ :param method: the method to call on the service
+ :param integer chunk: result size for each API call
+ :param \*args: same optional arguments that ``Client.call`` takes
+ :param \*\*kwargs: same optional keyword arguments that ``Client.call``
+ takes
+
+ Usage:
+ >>> gen = client['Account'].getVirtualGuests(iter=True)
+ >>> for virtual_guest in gen:
+ ... virtual_guest['id']
+ ...
+ 1234
+ 4321
+
+ """
+ return self.client.iter_call(self.name, name, *args, **kwargs)
__call__ = call
View
2 SoftLayer/__init__.py
@@ -13,8 +13,6 @@
:copyright: (c) 2013, SoftLayer Technologies, Inc. All rights reserved.
:license: BSD, see LICENSE for more details.
- :website: http://sldn.softlayer.com/article/Python
-
"""
from SoftLayer.consts import VERSION
View
80 SoftLayer/metadata.py
@@ -17,30 +17,46 @@
__all__ = ["MetadataManager"]
+METADATA_MAPPING = {
+ 'backend_mac': {'call': 'BackendMacAddresses'},
+ 'datacenter': {'call': 'Datacenter'},
+ 'datacenter_id': {'call': 'DatacenterId'},
+ 'domain': {'call': 'Domain'},
+ 'frontend_mac': {'call': 'FrontendMacAddresses'},
+ 'fqdn': {'call': 'FullyQualifiedDomainName'},
+ 'hostname': {'call': 'Hostname'},
+ 'id': {'call': 'Id'},
+ 'primary_backend_ip': {'call': 'PrimaryBackendIpAddress'},
+ 'primary_ip': {'call': 'PrimaryIpAddress'},
+ 'primary_frontend_ip': {'call': 'PrimaryIpAddress'},
+ 'provision_state': {'call': 'ProvisionState'},
+ 'router': {'call': 'Router', 'param_req': True},
+ 'tags': {'call': 'Tags'},
+ 'user_data': {'call': 'UserMetadata'},
+ 'user_metadata': {'call': 'UserMetadata'},
+ 'vlan_ids': {'call': 'VlanIds', 'param_req': True},
+ 'vlans': {'call': 'Vlans', 'param_req': True},
+}
+METADATA_ATTRIBUTES = METADATA_MAPPING.keys()
+
class MetadataManager(object):
- """ Manages metadata. """
-
- attribs = {
- 'backend_mac': {'call': 'BackendMacAddresses'},
- 'datacenter': {'call': 'Datacenter'},
- 'datacenter_id': {'call': 'DatacenterId'},
- 'domain': {'call': 'Domain'},
- 'frontend_mac': {'call': 'FrontendMacAddresses'},
- 'fqdn': {'call': 'FullyQualifiedDomainName'},
- 'hostname': {'call': 'Hostname'},
- 'id': {'call': 'Id'},
- 'primary_backend_ip': {'call': 'PrimaryBackendIpAddress'},
- 'primary_ip': {'call': 'PrimaryIpAddress'},
- 'primary_frontend_ip': {'call': 'PrimaryIpAddress'},
- 'provision_state': {'call': 'ProvisionState'},
- 'router': {'call': 'Router', 'param_req': True},
- 'tags': {'call': 'Tags'},
- 'user_data': {'call': 'UserMetadata'},
- 'user_metadata': {'call': 'UserMetadata'},
- 'vlan_ids': {'call': 'VlanIds', 'param_req': True},
- 'vlans': {'call': 'Vlans', 'param_req': True},
- }
+ """ Provides an interface for the metadata service. This provides metadata
+ about the resourse it is called from. See `METADATA_ATTRIBUTES` for
+ full list of attributes.
+
+ Usage:
+
+ >>> from SoftLayer.metadata import MetadataManager
+ >>> meta = MetadataManager(client)
+ >>> meta.get('datacenter')
+ 'dal05'
+ >>> meta.get('fqdn')
+ 'test.example.com'
+
+ """
+
+ attribs = METADATA_MAPPING
def __init__(self, client=None, timeout=5):
self.url = API_PRIVATE_ENDPOINT_REST.rstrip('/')
@@ -63,6 +79,12 @@ def make_request(self, path):
return resp.read()
def get(self, name, param=None):
+ """ Retreive a metadata attribute
+
+ :param name: name of the attribute to retrieve. See `attribs`
+ :param param: Required parameter for some attributes
+
+ """
if name not in self.attribs:
raise SoftLayerError('Unknown metadata attribute.')
@@ -100,7 +122,21 @@ def _get_network(self, kind, router=True, vlans=True, vlan_ids=True):
return network
def public_network(self, **kwargs):
+ """ Returns details about the public network
+
+ :param boolean router: True to return router details
+ :param boolean vlans: True to return vlan details
+ :param boolean vlan_ids: True to return vlan_ids
+
+ """
return self._get_network('frontend', **kwargs)
def private_network(self, **kwargs):
+ """ Returns details about the private network
+
+ :param boolean router: True to return router details
+ :param boolean vlans: True to return vlan details
+ :param boolean vlan_ids: True to return vlan_ids
+
+ """
return self._get_network('backend', **kwargs)
View
56 SoftLayer/tests/API/client_tests.py
@@ -270,68 +270,72 @@ def test_mask_call_invalid_mask(self, make_api_call):
else:
self.fail('No exception raised')
+ @patch('SoftLayer.API.Client.iter_call')
+ def test_iterate(self, _iter_call):
+ self.client['SERVICE'].METHOD(iter=True)
+ _iter_call.assert_called_with('SoftLayer_SERVICE', 'METHOD', iter=True)
+
+ @patch('SoftLayer.API.Client.iter_call')
+ def test_service_iter_call(self, _iter_call):
+ self.client['SERVICE'].iter_call('METHOD')
+ _iter_call.assert_called_with('SoftLayer_SERVICE', 'METHOD')
+
@patch('SoftLayer.API.Client.call')
- def test_iterate(self, _call):
+ def test_iter_call(self, _call):
# chunk=100, no limit
_call.side_effect = [range(100), range(100, 125)]
- result = list(self.client['SERVICE'].METHOD(iter=True))
+ result = list(self.client.iter_call('SERVICE', 'METHOD', iter=True))
self.assertEquals(range(125), result)
_call.assert_has_calls([
- call('SoftLayer_SERVICE', 'METHOD',
- limit=100, iter=True, offset=0),
- call('SoftLayer_SERVICE', 'METHOD',
- limit=100, iter=True, offset=100),
+ call('SERVICE', 'METHOD', limit=100, iter=False, offset=0),
+ call('SERVICE', 'METHOD', limit=100, iter=False, offset=100),
])
_call.reset_mock()
# chunk=100, no limit. Requires one extra request.
_call.side_effect = [range(100), range(100, 200), []]
- result = list(self.client['SERVICE'].METHOD(iter=True))
+ result = list(self.client.iter_call('SERVICE', 'METHOD', iter=True))
self.assertEquals(range(200), result)
_call.assert_has_calls([
- call('SoftLayer_SERVICE', 'METHOD',
- limit=100, iter=True, offset=0),
- call('SoftLayer_SERVICE', 'METHOD',
- limit=100, iter=True, offset=100),
- call('SoftLayer_SERVICE', 'METHOD',
- limit=100, iter=True, offset=200),
+ call('SERVICE', 'METHOD', limit=100, iter=False, offset=0),
+ call('SERVICE', 'METHOD', limit=100, iter=False, offset=100),
+ call('SERVICE', 'METHOD', limit=100, iter=False, offset=200),
])
_call.reset_mock()
# chunk=25, limit=30
_call.side_effect = [range(0, 25), range(25, 30)]
- result = list(
- self.client['SERVICE'].METHOD(iter=True, limit=30, chunk=25))
+ result = list(self.client.iter_call(
+ 'SERVICE', 'METHOD', iter=True, limit=30, chunk=25))
self.assertEquals(range(30), result)
_call.assert_has_calls([
- call('SoftLayer_SERVICE', 'METHOD', iter=True, limit=25, offset=0),
- call('SoftLayer_SERVICE', 'METHOD', iter=True, limit=5, offset=25),
+ call('SERVICE', 'METHOD', iter=False, limit=25, offset=0),
+ call('SERVICE', 'METHOD', iter=False, limit=5, offset=25),
])
_call.reset_mock()
# A non-list was returned
_call.side_effect = ["test"]
- result = list(self.client['SERVICE'].METHOD(iter=True))
+ result = list(self.client.iter_call('SERVICE', 'METHOD', iter=True))
self.assertEquals(["test"], result)
_call.assert_has_calls([
- call('SoftLayer_SERVICE', 'METHOD',
- iter=True, limit=100, offset=0),
+ call('SERVICE', 'METHOD', iter=False, limit=100, offset=0),
])
_call.reset_mock()
# chunk=25, limit=30, offset=12
_call.side_effect = [range(0, 25), range(25, 30)]
- result = list(self.client['SERVICE'].METHOD(
- iter=True, limit=30, chunk=25, offset=12))
+ result = list(self.client.iter_call(
+ 'SERVICE', 'METHOD', iter=True, limit=30, chunk=25, offset=12))
self.assertEquals(range(30), result)
_call.assert_has_calls([
- call('SoftLayer_SERVICE', 'METHOD',
- iter=True, limit=25, offset=12),
- call('SoftLayer_SERVICE', 'METHOD', iter=True, limit=5, offset=37),
+ call('SERVICE', 'METHOD', iter=False, limit=25, offset=12),
+ call('SERVICE', 'METHOD', iter=False, limit=5, offset=37),
])
# Chunk size of 0 is invalid
self.assertRaises(
AttributeError,
- lambda: list(self.client['SERVICE'].METHOD(iter=True, chunk=0)))
+ lambda: list(self.client.iter_call(
+ 'SERVICE', 'METHOD', iter=True, chunk=0)))
View
9 SoftLayer/utils.py
@@ -1,3 +1,12 @@
+"""
+ SoftLayer.utils
+ ~~~~~~~~~~~~~~~
+ Utility function/classes
+
+ :copyright: (c) 2013, SoftLayer Technologies, Inc. All rights reserved.
+ :license: BSD, see LICENSE for more details.
+"""
+
KNOWN_OPERATIONS = ['<=', '>=', '<', '>', '~', '*=', '^=', '$=', '_=', '!~']
View
153 docs/Makefile
@@ -0,0 +1,153 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = _build
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " singlehtml to make a single large HTML file"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " devhelp to make HTML files and a Devhelp project"
+ @echo " epub to make an epub"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
+ @echo " text to make text files"
+ @echo " man to make manual pages"
+ @echo " texinfo to make Texinfo files"
+ @echo " info to make Texinfo files and run them through makeinfo"
+ @echo " gettext to make PO message catalogs"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ -rm -rf $(BUILDDIR)/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+ @echo
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/SoftLayerAPIPythonClient.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/SoftLayerAPIPythonClient.qhc"
+
+devhelp:
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+ @echo
+ @echo "Build finished."
+ @echo "To view the help file:"
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/SoftLayerAPIPythonClient"
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/SoftLayerAPIPythonClient"
+ @echo "# devhelp"
+
+epub:
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+ @echo
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
+ "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through pdflatex..."
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+ @echo
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+ @echo
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+texinfo:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
+ @echo "Run \`make' in that directory to run these through makeinfo" \
+ "(use \`make info' here to do that automatically)."
+
+info:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo "Running Texinfo files through makeinfo..."
+ make -C $(BUILDDIR)/texinfo info
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
+
+gettext:
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
+ @echo
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
View
245 docs/api/client.rst
@@ -0,0 +1,245 @@
+.. _client:
+
+
+Developer Interface
+===================
+This is the primary API client to make API calls. It deals with constructing and executing XML-RPC calls against the SoftLayer API.
+
+Client setup
+------------
+You can pass in your username and api_key when creating a SoftLayer client instance. However, you can set these in the environmental variables 'SL_USERNAME' and 'SL_API_KEY'
+
+Creating a client instance by passing in the username/api_key:
+::
+
+ import SoftLayer
+ client = SoftLayer.Client(username='YOUR_USERNAME', api_key='YOUR_API_KEY')
+
+Creating a client instance with environmental variables set:
+::
+
+ # env variables
+ # SL_USERNAME = YOUR_USERNAME
+ # SL_API_KEY = YOUR_API_KEY
+ import SoftLayer
+ client = SoftLayer.Client()
+
+Below is an example of creating a client instance with more options. This will create a client with the private API endpoint (only accessable from the SoftLayer network), a timeout of 2 minutes, and with verbose mode on (prints out more than you ever wanted to know about the HTTP requests to stdout).
+::
+
+ client = SoftLayer.Client(
+ username='YOUR_USERNAME',
+ api_key='YOUR_API_KEY'
+ endpoint_url=SoftLayer.API_PRIVATE_ENDPOINT,
+ timeout=240,
+ verbose=True,
+ )
+
+Making API Calls
+----------------
+The SoftLayer API client for python leverages SoftLayer's XML-RPC API. It supports authentication, object masks, object filters, limits, offsets, and retrieving objects by id. The following section assumes you have a initialized client named 'client'.
+
+The best way to test our setup is to call the `getObject <http://sldn.softlayer.com/reference/services/SoftLayer_Account/getObject>`_ method on the `SoftLayer_Account <http://sldn.softlayer.com/reference/services/SoftLayer_Account>`_ service.
+::
+
+ client['Account'].getObject()
+
+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. To retrieve our extra information using an `object mask <http://sldn.softlayer.com/article/Extended-Object-Masks>`_.
+
+Retreive a ticket using Object Masks.
+::
+
+ ticket = client['Ticket'].getObject(
+ id=123456, mask="mask[updates, assignedUser, attachedHardware.datacenter]")
+
+
+Now add an update to the ticket.
+::
+
+ update = client['Ticket'].addUpdate({'entry' : 'Hello!'}, id=123456)
+
+Let's get a listing of virtual guests using the domain example.com
+::
+
+ client['Account'].getVirtualGuests(
+ filter={'virtualGuests': {'domain': {'operation': 'example.com'}}})
+
+This call gets tickets created between the beginning of March 1, 2013 and March 15, 2013.
+::
+
+ client['Account'].getTickets(
+ filter={
+ 'tickets': {
+ 'createDate': {
+ 'operation': 'betweenDate',
+ 'options': [
+ {'name': 'startDate', 'value': ['03/01/2013 0:0:0']},
+ {'name': 'endDate', 'value': ['03/15/2013 23:59:59']}
+ ]
+ }
+ }
+ }
+ )
+
+SoftLayer's XML-RPC API also allows for pagination.
+::
+
+ client['Account'].getVirtualGuests(limit=10, offset=0) # Page 1
+ client['Account'].getVirtualGuests(limit=10, offset=10) # Page 2
+
+Here's how to create a new Cloud Compute Instance using `SoftLayer_Virtual_Guest.createObject <http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/createObject>`_. Be warned, this call actually creates an hourly CCI so this does have billing implications.
+::
+
+ client['Virtual_Guest'].createObject({
+ 'hostname': 'myhostname',
+ 'domain': 'example.com',
+ 'startCpus': 1,
+ 'maxMemory': 1024,
+ 'hourlyBillingFlag': 'true',
+ 'operatingSystemReferenceCode': 'UBUNTU_LATEST',
+ 'localDiskFlag': 'false'
+ })
+
+
+API Reference
+-------------
+.. autoclass:: SoftLayer.Client
+ :members:
+ :undoc-members:
+
+ .. automethod:: SoftLayer.Client.__getitem__
+
+.. autoclass:: SoftLayer.API.Service
+ :members:
+ :undoc-members:
+
+ .. automethod:: SoftLayer.API.Service.__call__
+
+
+.. automodule:: SoftLayer.exceptions
+ :members:
+ :undoc-members:
+
+
+Backwards Compatibility
+-----------------------
+If you've been using the older Python client (<2.0), you'll be happy to know that the old API is still currently working. However, you should deprecate use of the old stuff. Below is an example of the old API converted to the new one.
+
+::
+
+ import SoftLayer.API
+ client = SoftLayer.API.Client('SoftLayer_Account', None, 'username', 'api_key')
+ client.set_object_mask({'ipAddresses' : None})
+ client.set_result_limit(10, offset=10)
+ client.getObject()
+
+... changes to ...
+::
+
+ import SoftLayer
+ client = SoftLayer.Client(username='username', api_key='api_key')
+ client['Account'].getObject(mask="mask[ipAddresses]", limit=10, offset=0)
+
+Deprecated APIs
+^^^^^^^^^^^^^^^
+Below are examples of how the old usages to the new API.
+
+**Importing the module**
+::
+
+ # Old
+ import SoftLayer.API
+
+ # New
+ import SoftLayer
+
+**Creating a client instance**
+::
+
+ # Old
+ client = SoftLayer.API.Client('SoftLayer_Account', None, 'username', 'api_key')
+
+ # New
+ client = SoftLayer.Client(username='username', api_key='api_key')
+ service = client['Account']
+
+**Making an API call**
+::
+
+ # Old
+ client = SoftLayer.API.Client('SoftLayer_Account', None, 'username', 'api_key')
+ client.getObject()
+
+ # New
+ client = SoftLayer.Client(username='username', api_key='api_key')
+ client['Account'].getObject()
+
+ # Optionally
+ service = client['Account']
+ service.getObject()
+
+**Setting Object Mask**
+::
+
+ # Old
+ client.set_object_mask({'ipAddresses' : None})
+
+ # New
+ client['Account'].getObject(mask="mask[ipAddresses]")
+
+**Using Init Parameter**
+::
+
+ # Old
+ client.set_init_parameter(1234)
+
+ # New
+ client['Account'].getObject(id=1234)
+
+**Setting Result Limit and Offset**
+::
+
+ # Old
+ client.set_result_limit(10, offset=10)
+
+ # New
+ client['Account'].getObject(limit=10, offset=10)
+
+**Adding Additional Headers**
+::
+
+ # Old
+ # These headers are persisted accross API calls
+ client.add_header('header', 'value')
+
+ # New
+ # These headers are NOT persisted accross API calls
+ client['Account'].getObject(headers={'header': 'value'})
+
+**Removing Additional Headers**
+::
+
+ # Old
+ client.remove_header('header')
+
+ # New
+ client['Account'].getObject()
+
+**Adding Additional HTTP Headers**
+::
+
+ # Old
+ client.add_raw_header('header', 'value')
+
+ # New
+ client['Account'].getObject(raw_headers={'header': 'value'})
+
+**Changing Authentication Credentials**
+::
+
+ # Old
+ client.set_authentication('username', 'api_key')
+
+ # New
+ client.username = 'username'
+ client.api_key = 'api_key'
View
5 docs/api/managers/cci.rst
@@ -0,0 +1,5 @@
+.. _cci:
+
+.. automodule:: SoftLayer.CCI
+ :members:
+ :undoc-members:
View
5 docs/api/managers/dns.rst
@@ -0,0 +1,5 @@
+.. _dns:
+
+.. automodule:: SoftLayer.DNS
+ :members:
+ :undoc-members:
View
5 docs/api/managers/firewall.rst
@@ -0,0 +1,5 @@
+.. _firewall:
+
+.. automodule:: SoftLayer.firewall
+ :members:
+ :undoc-members:
View
7 docs/api/managers/metadata.rst
@@ -0,0 +1,7 @@
+.. _metadata:
+
+.. automodule:: SoftLayer.metadata
+ :members:
+ :undoc-members:
+
+.. autoattribute:: SoftLayer.metadata.METADATA_ATTRIBUTES
View
5 docs/api/managers/ssl.rst
@@ -0,0 +1,5 @@
+.. _ssl:
+
+.. automodule:: SoftLayer.SSL
+ :members:
+ :undoc-members:
View
243 docs/conf.py
@@ -0,0 +1,243 @@
+# -*- coding: utf-8 -*-
+#
+# SoftLayer API Python Client documentation build configuration file, created by
+# sphinx-quickstart on Fri Mar 22 11:08:48 2013.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+# sys.path.insert(0, os.path.abspath('.'))
+sys.path.insert(0, os.path.abspath('..'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'SoftLayer API Python Client'
+copyright = u'2013, SoftLayer Technologies, Inc.'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '2.1.0'
+# The full version, including alpha/beta/rc tags.
+release = '2.1.0'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'friendly'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'nature'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'SoftLayerAPIPythonClientdoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'SoftLayerAPIPythonClient.tex', u'SoftLayer API Python Client Documentation',
+ u'SoftLayer Technologies, Inc.', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ ('index', 'softlayerapipythonclient', u'SoftLayer API Python Client Documentation',
+ [u'SoftLayer Technologies, Inc.'], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output ------------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ ('index', 'SoftLayerAPIPythonClient', u'SoftLayer API Python Client Documentation',
+ u'SoftLayer Technologies, Inc.', 'SoftLayerAPIPythonClient', 'One line description of project.',
+ 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
View
48 docs/index.rst
@@ -0,0 +1,48 @@
+.. SoftLayer API Python Client documentation
+
+SoftLayer API Python Client
+===========================
+This is the documentation to SoftLayer's Python API Bindings. These bindings use SoftLayer's `XML-RPC interface <http://sldn.softlayer.com/article/XML-RPC>`_ in order to manage SoftLayer services.
+
+Release v\ |version|. (:ref:`Installation <install>`)
+
+API Documentation
+-----------------
+.. toctree::
+ :maxdepth: 2
+
+ install
+ api/client
+
+::
+
+ >>> import SoftLayer
+ >>> client = SoftLayer.Client(username="username", api_key="api_key")
+ >>> resp = client['Account'].getObject()
+ >>> resp['companyName']
+ 'Your Company'
+
+Managers
+--------
+Managers mask out a lot of the complexities of using the API into classes that provide a simpler interface to various services.
+
+.. toctree::
+ :maxdepth: 1
+ :glob:
+
+ api/managers/*
+
+::
+
+ >>> from SoftLayer.CCI import CCIManager
+ >>> cci = CCIManager(client)
+ >>> cci.list_instances()
+ [...]
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
View
39 docs/install.rst
@@ -0,0 +1,39 @@
+.. _install:
+
+Installation
+============
+Install via pip: ::
+
+ $ pip install softlayer
+
+Install from source gia pip (requires git): ::
+
+ $ pip install git+git://github.com/softlayer/softlayer-api-python-client.git
+
+The most up to date version of this library can be found on the SoftLayer GitHub public repositories: http://github.com/softlayer. Please post to the SoftLayer forums http://forums.softlayer.com/ or open a support ticket in the SoftLayer customer portal if you have any questions regarding use of this library.
+
+
+
+Get the Code
+------------
+
+The project is developed on GitHub, at `github.com/softlayer/softlayer-api-python-client <https://github.com/softlayer/softlayer-api-python-client>`_.
+
+
+You can clone the public repository::
+
+ git clone git://github.com/softlayer/softlayer-api-python-client.git
+
+Or, Download the `tarball <https://github.com/softlayer/softlayer-api-python-client/tarball/master>`_::
+
+ $ curl -OL https://github.com/softlayer/softlayer-api-python-client/tarball/master
+
+Or, download the `zipball <https://github.com/softlayer/softlayer-api-python-client/zipball/master>`_::
+
+ $ curl -OL https://github.com/softlayer/softlayer-api-python-client/zipball/master
+
+
+Once you have a copy of the source, you can embed it in your Python package,
+or install it into your site-packages easily::
+
+ $ python setup.py install
View
25 fabfile.py
@@ -0,0 +1,25 @@
+from fabric.api import local, lcd, settings
+
+
+def publish_docs():
+ " Publishes docs to github via github pages. "
+ with lcd('docs'):
+ with settings(warn_only=True):
+ local('rm -rf _build/html')
+ local('mkdir -p _build/html')
+ local('git clone -b gh-pages '
+ 'git@github.com:softlayer/softlayer-api-python-client.git '
+ '_build/html')
+ local('make html')
+ with lcd('_build/html'):
+ local('touch .nojekyll')
+ local('git add .nojekyll')
+ local('git add -u')
+ local('git commit -m "Documentation Build"')
+ local('git push origin gh-pages')
+
+
+def make_html():
+ "Build HTML docs"
+ with lcd('docs'):
+ local('make html')
View
2 requirements.txt
@@ -2,4 +2,4 @@ tox
nose
mock
coverage
-sphinx
+sphinx

0 comments on commit 81c0da8

Please sign in to comment.