Exemplo n.º 1
0
    def __getattr__(self, key):
        """Load values for anything that doesn't get loaded by default.

        For user_data and notes, a secondary API call is needed. Only make that
        call when the info is requested.
        """
        if key == 'user_data':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            user_json = api.rest(self.url + '/user_data.json')
            self.data['user_data'] = UserData(json.loads(user_json), self.url)
            return self.user_data

        if key == 'notes':
            api = ApiClient()
            notes_json = api.rest(self.url + '/notes.json')
            self.notes = Notes(notes_json, self.url)
            return self.notes

        if key == 'labels':
            api = ApiClient()
            labels_json = api.rest(self.url + '/labels')
            self.labels = Labels(labels_json, self.url)
            return self.labels

        return super(Environment, self).__getattr__(key)
Exemplo n.º 2
0
    def add_user(self, user):
        """Add a :class:`User` to the group.

        Args:
            user (int): id of the user to add.

        Raises:
            TypeError: If user is not an :class:`int`.
            KeyError: If user is not in :class:`Users` list.

        Returns:
            bool: True if the user was added.

        Example:
            >>> groups = skytap.Groups()
            >>> users = skytap.Users()
            >>> for u in users:
            ...     groups[12345].add(u.id)
        """
        if type(user) is not int:
            raise TypeError('User must be an int.')

        Utils.info('Adding user ' + str(user) + ' to group: ' + self.name)
        api = ApiClient()
        api.rest(self.url + '/users/' + str(user) + '.json',
                 {},
                 'PUT')
        self.refresh()
        return user in self.users
Exemplo n.º 3
0
    def __getattr__(self, key):
        """Load values for anything that doesn't get loaded by default.

        For user_data, notes, and interfaces, a secondary API call is needed.
        Only make that call when the info is requested.
        """
        if key == 'user_data':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            user_json = api.rest(self.url + '/user_data.json')
            self.user_data = UserData(json.loads(user_json), self.url)
            return self.user_data

        if key == 'notes':
            api = ApiClient()
            notes_json = api.rest(self.url + '/notes.json')
            self.notes = Notes(notes_json, self.url)
            return self.notes

        if key == 'interfaces':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            interfaces_json = json.loads(api.rest(self.url))
            self.interfaces = Interfaces(interfaces_json["interfaces"],
                                         self.url)
            return self.interfaces

        return super(Vm, self).__getattr__(key)
Exemplo n.º 4
0
    def add_user(self, user):
        """Add a :class:`User` to the group.

        Args:
            user (int): id of the user to add.

        Raises:
            TypeError: If user is not an :class:`int`.
            KeyError: If user is not in :class:`Users` list.

        Returns:
            bool: True if the user was added.

        Example:
            >>> groups = skytap.Groups()
            >>> users = skytap.Users()
            >>> for u in users:
            ...     groups[12345].add(u.id)
        """
        if type(user) is not int:
            raise TypeError('User must be an int.')

        Utils.info('Adding user ' + str(user) + ' to group: ' + self.name)
        api = ApiClient()
        api.rest(self.url + '/users/' + str(user) + '.json', {}, 'PUT')
        self.refresh()
        return user in self.users
Exemplo n.º 5
0
    def change_state(self, state, wait=False):
        """Change the state of the object (environment/vm)."""
        if state not in Suspendable.valid_states:
            raise ValueError(str(state) + ' not a valid state.')

        self.refresh()
        if self.runstate == state:
            return True

        if Config.add_note_on_state_change:
            self.notes.add("Changing state via API to '" + state + "'")

        api = ApiClient()
        url = self.url + '.json'
        data = {"runstate": state}
        api.rest(url, {}, 'PUT', data)
        if not wait:
            return True

        if state == 'reset':
            state = 'running'

        if state == 'halted':
            state = 'stopped'

        self.refresh()
        counter = 0
        while not self.runstate == state and counter < 12:
            time.sleep(10)
            self.refresh()
        if self.runstate == state:
            return True
        return False
Exemplo n.º 6
0
    def __getattr__(self, key):
        """Load values for anything that doesn't get loaded by default.

        For user_data and notes, a secondary API call is needed. Only make that
        call when the info is requested.
        """
        if key == 'user_data':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            user_json = api.rest(self.url + '/user_data.json')
            self.data['user_data'] = UserData(json.loads(user_json), self.url)
            return self.user_data

        if key == 'notes':
            api = ApiClient()
            notes_json = api.rest(self.url + '/notes.json')
            self.notes = Notes(notes_json, self.url)
            return self.notes

        if key == 'labels':
            api = ApiClient()
            labels_json = api.rest(self.url + '/labels')
            self.labels = Labels(labels_json, self.url)
            return self.labels

        return super(Environment, self).__getattr__(key)
Exemplo n.º 7
0
    def remove_user(self, user):
        """Remove a :class:`user` from the group.

        Args:
            user (int): id of the user to remove.

        Raises:
            TypeError: If user is not an :class:`int`.
            KeyError: If user is not in :class:`Users` list.

        Returns:
            bool: True if the user was removed.

        Example:
            >>> groups = skytap.Groups()
            >>> groups[1234].remove_user(12345)
        """
        if type(user) is not int:
            raise TypeError('User must be an int.')

        Utils.info('Removing user ' + str(user) +
                   ' from group: ' + self.name)
        api = ApiClient()
        api.rest(self.url + '/users/' + str(user),
                 {},
                 'DELETE')

        self.refresh()
        return user not in self.users
Exemplo n.º 8
0
    def remove_user(self, user):
        """Remove a :class:`user` from the group.

        Args:
            user (int): id of the user to remove.

        Raises:
            TypeError: If user is not an :class:`int`.
            KeyError: If user is not in :class:`Users` list.

        Returns:
            bool: True if the user was removed.

        Example:
            >>> groups = skytap.Groups()
            >>> groups[1234].remove_user(12345)
        """
        if type(user) is not int:
            raise TypeError('User must be an int.')

        Utils.info('Removing user ' + str(user) + ' from group: ' + self.name)
        api = ApiClient()
        api.rest(self.url + '/users/' + str(user), {}, 'DELETE')

        self.refresh()
        return user not in self.users
Exemplo n.º 9
0
    def add(self, login_name, email=None):
        """Add one user.

        Args:
            login_name (str): The login id of the account, usually an email.
            email (str): The email of the account. If blank, will use
                login_name.

        Returns:
            int: The new user id from Skytap.

        Example:

        .. code-block:: python

            users = skytap.Users()
            new_user = users.add('*****@*****.**')
            print(users[new_user].login_name)
        """
        Utils.info('Adding user: '******'.json'
        response = api.rest(url, data, 'POST')
        new_user = json.loads(response)
        self.refresh()
        if 'id' in new_user:
            return int(new_user['id'])
        Utils.warning('Trying to create user (' + login_name + '), but ' +
                      'got an unexpected return from Skytap. Response:\n' +
                      response)
        return 0
Exemplo n.º 10
0
    def add(self, login_name, email=None):
        """Add one user.

        Args:
            login_name (str): The login id of the account, usually an email.
            email (str): The email of the account. If blank, will use
                login_name.

        Returns:
            int: The new user id from Skytap.

        Example:

        .. code-block:: python

            users = skytap.Users()
            new_user = users.add('*****@*****.**')
            print(users[new_user].login_name)
        """
        Utils.info('Adding user: '******'.json'
        response = api.rest(url, data, 'POST')
        new_user = json.loads(response)
        self.refresh()
        if 'id' in new_user:
            return int(new_user['id'])
        Utils.warning('Trying to create user (' + login_name + '), but ' +
                      'got an unexpected return from Skytap. Response:\n' +
                      response)
        return 0
Exemplo n.º 11
0
 def refresh(self):
     """Refresh the data in our object, if we have a URL to pull from."""
     if 'url' not in self.data:
         return KeyError
     api = ApiClient()
     env_json = api.rest(self.url)
     self.__init__(json.loads(env_json))
Exemplo n.º 12
0
    def delete_line(self, line):
        """Delete line from environment's userdata.

        Args:
            line (int): line number to delete.

        Returns:
            str: The response from Skytap.
        """
        line = str(line)

        lines = self.contents.split("\n")

        new_content = ""

        for i in lines:
            if i != "":
                if i.strip() != line.strip():
                    new_content += (i.strip() + "\n")

        Utils.info('Removing line: \"' + str(line) + '\"')
        api = ApiClient()
        data = {"contents": new_content.lstrip()}
        response = api.rest(self.url, data, 'POST')
        self.refresh()
        return response
Exemplo n.º 13
0
    def add(self, key, value):
        """Add value to environment's userdata.

        Args:
            key (str): The name of the value's key.
            value (str): The value to add.

        Returns:
            str: The response from Skytap, or "{}".
        """
        add_key = True

        lines = self.contents.split("\n")

        for i in lines:
            if i != "":
                j = i.split()
                if len(j) > 0 and j[0] == (key + ":"):
                    add_key = False

        if add_key:
            Utils.info('Adding key \"' + key + '\" with value \"'
                       '' + value + '\"')
            api = ApiClient()
            new_content = "" + key + ": " + value + "\n" + self.contents
            data = {"contents": new_content}
            response = api.rest(self.url, data, 'POST')
            self.data[key] = value
            self.refresh()
            return response
        else:
            Utils.info('Key \"' + key + '\" with value \"' + value + '\"'
                       'already exists.')
            return "{}"
Exemplo n.º 14
0
    def delete(self, key):
        """Delete key/value from environment's userdata.

        Args:
            key (str): The name of key to delete, along with value

        Returns:
            str: The response from Skytap, or "{}".
        """
        new_content = ""

        del_key = False

        lines = self.contents.split("\n")

        for i in lines:
            if i != "":
                j = i.split()
                if len(j) > 0 and j[0] == (key + ":"):
                    del_key = True
                else:
                    new_content += (i.strip() + "\n")

        if del_key:
            Utils.info('Deleting key \"' + key + '\".')
            api = ApiClient()
            data = {"contents": "" + new_content}
            response = api.rest(self.url, data, 'POST')
            self.refresh()
            return response
        else:
            Utils.info('Key \"' + key + '\" already exists.')
            return "{}"
Exemplo n.º 15
0
 def refresh(self):
     """Refresh the data in our object, if we have a URL to pull from."""
     if 'url' not in self.data:
         return KeyError
     api = ApiClient()
     env_json = api.rest(self.url)
     self.__init__(json.loads(env_json))
Exemplo n.º 16
0
    def delete(self, key):
        """Delete key/value from environment's userdata.

        Args:
            key (str): The name of key to delete, along with value

        Returns:
            str: The response from Skytap, or "{}".
        """
        new_content = ""

        del_key = False

        lines = self.contents.split("\n")

        for i in lines:
            if i != "":
                j = i.split()
                if len(j) > 0 and j[0] == (key + ":"):
                    del_key = True
                else:
                    new_content += (i.strip() + "\n")

        if del_key:
            Utils.info('Deleting key \"' + key + '\".')
            api = ApiClient()
            data = {"contents": "" + new_content}
            response = api.rest(self.url, data, 'POST')
            self.refresh()
            return response
        else:
            Utils.info('Key \"' + key + '\" already exists.')
            return "{}"
Exemplo n.º 17
0
    def add(self, group, description=''):
        """Add one group.

        Args:
            group (str): The group name to add.
            description (str): The group description to add.

        Returns:
            int: The new group id from Skytap.

        Example:

        .. code-block:: python

            groups = skytap.Groups()
            new_group = groups.add('muppets', 'felt covered friends')
            print(groups[new_group].name)
        """
        Utils.info('Adding group: ' + group)
        api = ApiClient()
        data = {"name": group,
                "description": description}
        url = self.url + '.json'
        response = api.rest(url, data, 'POST')
        new_group = json.loads(response)
        self.refresh()
        if 'id' in new_group:
            return int(new_group['id'])
        Utils.warning('Trying to create group (' + group + '), but ' +
                      'got an unexpected return from Skytap. Response:\n' +
                      response)
        return 0
Exemplo n.º 18
0
    def add(self, key, value):
        """Add value to environment's userdata.

        Args:
            key (str): The name of the value's key.
            value (str): The value to add.

        Returns:
            str: The response from Skytap, or "{}".
        """
        add_key = True

        lines = self.contents.split("\n")

        for i in lines:
            if i != "":
                j = i.split()
                if len(j) > 0 and j[0] == (key + ":"):
                    add_key = False

        if add_key:
            Utils.info('Adding key \"' + key + '\" with value \"'
                       '' + value + '\"')
            api = ApiClient()
            new_content = "" + key + ": " + value + "\n" + self.contents
            data = {"contents": new_content}
            response = api.rest(self.url, data, 'POST')
            self.data[key] = value
            self.refresh()
            return response
        else:
            Utils.info('Key \"' + key + '\" with value \"' + value + '\"'
                       'already exists.')
            return "{}"
Exemplo n.º 19
0
    def delete_line(self, line):
        """Delete line from environment's userdata.

        Args:
            line (int): line number to delete.

        Returns:
            str: The response from Skytap.
        """
        line = str(line)

        lines = self.contents.split("\n")

        new_content = ""

        for i in lines:
            if i != "":
                if i.strip() != line.strip():
                    new_content += (i.strip() + "\n")

        Utils.info('Removing line: \"' + str(line) + '\"')
        api = ApiClient()
        data = {"contents": new_content.lstrip()}
        response = api.rest(self.url, data, 'POST')
        self.refresh()
        return response
Exemplo n.º 20
0
 def delete(self):
     """Delete this export job."""
     Utils.info('Deleting job ' + str(self.id) + ' from queue.')
     api = ApiClient()
     response = api.rest(self.url,
              {},
              'DELETE')
     return response
Exemplo n.º 21
0
 def delete(self):
     """Delete the group."""
     Utils.info('Deleting group: ' +
                str(self.id) + ' (' + self.name + ')')
     api = ApiClient()
     response = api.rest(self.url_v1,
                         {},
                         'DELETE')
     return response
Exemplo n.º 22
0
    def __getattr__(self, key):
        if key == 'services':
            api = ApiClient()
            services_json = json.loads(api.rest(self.url))
            self.services = PublishedServices(services_json["services"],
                                              self.url)
            return self.services

        return super(Interface, self).__getattr__(key)
Exemplo n.º 23
0
class TestApiClient(object):
    def setUp(self):
        self.api_client = ApiClient()

    def test_does_basic_call_return_json(self):
        """Some basic testing of the API client."""
        response = self.api_client.rest('/v2/configurations')
        json_check = json.loads(response)
        assert len(json_check) > 0, "JSON didn't result in any rows"
Exemplo n.º 24
0
Arquivo: Vm.py Projeto: wolf637/skytap
    def delete(self):
        """Delete a VM.

        In general, it'd seem wise not to do this very often.
        """
        Utils.info('Deleting VM: ' + str(self.id) + '(' + self.name + ')')
        api = ApiClient()
        response = api.rest(self.url, {}, 'DELETE')
        return response
Exemplo n.º 25
0
    def enable(self, label_id):
        """Enable a label category."""
        if not self.url.endswith("label_categories"):
            return "Can only enable label categories."

        Utils.info("Enabling label category of id " + str(label_id) + ".")
        api = ApiClient()
        data = {"enabled": "True"}
        response = api.rest(self.url + "/" + str(label_id), data, "PUT")
        self.refresh()
        return response
Exemplo n.º 26
0
    def delete(self):
        """Delete a VM.

        In general, it'd seem wise not to do this very often.
        """
        Utils.info('Deleting VM: ' + str(self.id) + '(' + self.name + ')')
        api = ApiClient()
        response = api.rest(self.url,
                            {},
                            'DELETE')
        return response
Exemplo n.º 27
0
    def disable(self, label_id):
        """Disable a label category (the closest thing to deleting)."""
        if not self.url.endswith("label_categories"):
            return "Can only disable label categories."

        Utils.info("Disabling label category of id " + str(label_id) + ".")
        api = ApiClient()
        data = {"enabled": "False"}
        response = api.rest(self.url + "/" + str(label_id), data, "PUT")
        self.refresh()
        return response
Exemplo n.º 28
0
    def enable(self, label_id):
        """Enable a label category."""
        if not self.url.endswith("label_categories"):
            return "Can only enable label categories."

        Utils.info("Enabling label category of id " + str(label_id) + ".")
        api = ApiClient()
        data = {"enabled": "True"}
        response = api.rest(self.url + "/" + str(label_id), data, "PUT")
        self.refresh()
        return response
Exemplo n.º 29
0
    def disable(self, label_id):
        """Disable a label category (the closest thing to deleting)."""
        if not self.url.endswith("label_categories"):
            return "Can only disable label categories."

        Utils.info("Disabling label category of id " + str(label_id) + ".")
        api = ApiClient()
        data = {"enabled": "False"}
        response = api.rest(self.url + "/" + str(label_id), data, "PUT")
        self.refresh()
        return response
Exemplo n.º 30
0
    def add(self, value, category):
        """Add label to environment or VM."""
        if self.url.endswith("label_categories"):
            return "Cannot add label. Did you mean to use \"create()\"?"

        Utils.info("Adding Label to " + category + " with value " + value +
                   ".")
        api = ApiClient()
        data = [{"label_category": category, "value": value}]
        response = api.rest(self.url, data, "PUT")
        self.refresh()
        return response
Exemplo n.º 31
0
    def create(self, name, single_value):
        """Create label that is single or multi-valued."""
        if not self.url.endswith("label_categories"):
            return "Cannot create label. Did you mean to use \"add()\"?"

        Utils.info("Creating Label: " + name + ""
                   ". Single-value: " + str(single_value))
        api = ApiClient()
        data = [{"name": name, "single-value": single_value}]
        response = api.rest(self.url, data, "POST")
        self.refresh()
        return response
Exemplo n.º 32
0
    def create(self, name, single_value):
        """Create label that is single or multi-valued."""
        if not self.url.endswith("label_categories"):
            return "Cannot create label. Did you mean to use \"add()\"?"

        Utils.info("Creating Label: " + name + ""
                   ". Single-value: " + str(single_value))
        api = ApiClient()
        data = [{"name": name, "single-value": single_value}]
        response = api.rest(self.url, data, "POST")
        self.refresh()
        return response
Exemplo n.º 33
0
    def add(self, value, category):
        """Add label to environment or VM."""
        if self.url.endswith("label_categories"):
            return "Cannot add label. Did you mean to use \"create()\"?"

        Utils.info("Adding Label to " +
                   category +
                   " with value " +
                   value + ".")
        api = ApiClient()
        data = [{"label_category": category, "value": value}]
        response = api.rest(self.url, data, "PUT")
        self.refresh()
        return response
Exemplo n.º 34
0
    def add(self, note):
        """Add one note.

        Args:
            note (str): The note text to add.

        Returns:
            str: The response from Skytap, typically the new note.
        """
        Utils.info('Adding note: ' + note)
        api = ApiClient()
        data = {"text": note}
        response = api.rest(self.url, data, 'POST')
        self.refresh()
        return response
Exemplo n.º 35
0
    def __getattr__(self, key):
        """Load values for anything that doesn't get loaded by default.

        For user_data and notes, a secondary API call is needed. Only make that
        call when the info is requested.
        """
        if key == 'users':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            user_json = api.rest(self.url)
            self.data['users'] = Users(json.loads(user_json)['users'])
            return self.users

        return super(Group, self).__getattr__(key)
Exemplo n.º 36
0
    def delete(self, transfer_user):
        """Delete the user."""
        if isinstance(transfer_user, User):
            transfer_user = transfer_user.id
        if not isinstance(transfer_user, int):
            raise TypeError('transfer_user must be a User or int.')
        Utils.info('Deleting user: '******' (' + self.name +
                   ') and transferring ' + 'resources to user id: ' +
                   str(transfer_user))
        api = ApiClient()

        transfer = {"transfer_user_id": str(transfer_user)}

        response = api.rest(self.url, transfer, 'DELETE')
        return response
Exemplo n.º 37
0
    def __getattr__(self, key):
        """Load values for anything that doesn't get loaded by default.

        For user_data, a secondary API call is needed. Only make that
        call when the info is requested.
        """
        if key == 'user_data':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            user_json = api.rest(self.url + '/user_data.json')
            self.user_data = UserData(json.loads(user_json))
            return self.user_data

        return super(Template, self).__getattr__(key)
Exemplo n.º 38
0
    def __getattr__(self, key):
        """Load values for anything that doesn't get loaded by default.

        For user_data, a secondary API call is needed. Only make that
        call when the info is requested.
        """
        if key == 'user_data':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            user_json = api.rest(self.url + '/user_data.json')
            self.user_data = UserData(json.loads(user_json), self.url)
            return self.user_data

        return super(Template, self).__getattr__(key)
Exemplo n.º 39
0
    def __getattr__(self, key):
        """Load values for anything that doesn't get loaded by default.

        For user_data and notes, a secondary API call is needed. Only make that
        call when the info is requested.
        """
        if key == 'users':
            if key in self.data:
                return self.data[key]
            api = ApiClient()
            user_json = api.rest(self.url)
            self.data['users'] = Users(json.loads(user_json)['users'])
            return self.users

        return super(Group, self).__getattr__(key)
Exemplo n.º 40
0
    def refresh(self):
        """Refresh the notes.

        Raises:
            KeyError: if the Notes object doesn't
                have a url attribute for some reason.

        Go back to Skytap and get the notes again. Useful when you've changed
        the notes and to make sure you're current.
        """
        if len(self.url) == 0:
            return KeyError
        api = ApiClient()
        note_json = api.rest(self.url)
        self.load_list_from_json(note_json, Note)
Exemplo n.º 41
0
    def delete(self, transfer_user):
        """Delete the user."""
        if isinstance(transfer_user, User):
            transfer_user = transfer_user.id
        if not isinstance(transfer_user, int):
            raise TypeError('transfer_user must be a User or int.')
        Utils.info('Deleting user: '******' (' + self.name + ') and transferring ' +
                   'resources to user id: ' + str(transfer_user))
        api = ApiClient()

        transfer = {"transfer_user_id": str(transfer_user)}

        response = api.rest(self.url,
                            transfer,
                            'DELETE')
        return response
Exemplo n.º 42
0
    def create(self, vmid):
        """Create an export job from a vm in a template."""
        if type(vmid) is not int:
            raise TypeError('vmid must be an int')

        Utils.info('creating export job for VM ' + str(vmid))
        api = ApiClient()
        data = {"vm_id": vmid}
        url = self.url + '.json'
        response = api.rest(url, data, "POST")
        exports = json.loads(response)
        self.refresh()
        if 'id' in exports:
            return int(exports['id'])
        Utils.warning('Trying to create new export job from VM ' + vmid +
                      ', but got an unexpected response from Skytap. ' +
                      'Response:\n' + response)
        return 0
Exemplo n.º 43
0
    def create(self, vmid):
        """Create an export job from a vm in a template."""
        if type(vmid) is not int:
            raise TypeError('vmid must be an int')

        Utils.info('creating export job for VM ' + str(vmid))
        api = ApiClient()
        data = {"vm_id": vmid}
        url = self.url + '.json'
        response = api.rest(url, data, "POST")
        exports = json.loads(response)
        self.refresh()
        if 'id' in exports:
            return int(exports['id'])
        Utils.warning('Trying to create new export job from VM ' + vmid +
                      ', but got an unexpected response from Skytap. ' +
                      'Response:\n' + response)
        return 0
Exemplo n.º 44
0
    def add_line(self, text, line=-1):
        """Add line to environment's userdata.

        Args:
            text (str): line of text to be added. (Required)
            line (int): line number to add to. If too large, default to last.

        Returns:
            str: The response from Skytap.
        """
        try:
            line = int(line)
        except ValueError:
            return "{}"  # Not an integer

        lines = self.contents.split("\n")

        new_content = ""

        line_found = False
        count = 0
        for i in lines:
            if i != "":
                if line == count:
                    new_content += (text.strip() + "\n")

                    new_content += (i.strip() + "\n")

                    line_found = True
                else:
                    new_content += (i.strip() + "\n")

            count += 1

        if not line_found:
            new_content += (text.strip() + "\n")

        Utils.info('Adding line: \"' + text + '\"')
        api = ApiClient()
        data = {"contents": new_content}
        response = api.rest(self.url, data, 'POST')
        self.refresh()
        return response
Exemplo n.º 45
0
    def add_line(self, text, line=-1):
        """Add line to environment's userdata.

        Args:
            text (str): line of text to be added. (Required)
            line (int): line number to add to. If too large, default to last.

        Returns:
            str: The response from Skytap.
        """
        try:
            line = int(line)
        except ValueError:
            return "{}"  # Not an integer

        lines = self.contents.split("\n")

        new_content = ""

        line_found = False
        count = 0
        for i in lines:
            if i != "":
                if line == count:
                    new_content += (text.strip() + "\n")

                    new_content += (i.strip() + "\n")

                    line_found = True
                else:
                    new_content += (i.strip() + "\n")

            count += 1

        if not line_found:
            new_content += (text.strip() + "\n")

        Utils.info('Adding line: \"' + text + '\"')
        api = ApiClient()
        data = {"contents": new_content}
        response = api.rest(self.url, data, 'POST')
        self.refresh()
        return response
Exemplo n.º 46
0
    def delete(self, note):
        """Delete one note.

        Args:
            note: The :class:`~skytap.models.Note` to delete.

        Returns:
            str: The response from Skytap.

        Raises:
            TypeError: If note is not a Note object.
        """
        if note is None:
            return False
        if not isinstance(note, Note):
            raise TypeError
        Utils.info('Deleting note ID: ' + str(note.id))
        api = ApiClient()
        url = self.url.replace('.json', '/' + str(note.id))
        response = api.rest(url,
                            {},
                            'DELETE')
        self.refresh()
        return response
Exemplo n.º 47
0
    def __getattr__(self, key):
        """Get attributes.

        Interfaces aren't fully returned when the API call is made -
        Published Services aren't returned. Often this doesn't matter,
        so we don't automatically pull this information. However, if you ask
        for the services, this function will go and get the requested
        information on demand. This allows saving of API calls (we don't
        request this unless you're accessing Published Services), but also
        you can treat the object as if the services are there all along. We'll
        get the info when you ask for it, and you can move along like it was
        there from the start.

        If you're doing anything other than asking for services, then this
        passes the call upstream to do the default stuff.
        """
        if key == 'services':
            api = ApiClient()
            services_json = json.loads(api.rest(self.url))
            self.services = PublishedServices(services_json["services"],
                                              self.url)
            return self.services

        return super(Interface, self).__getattr__(key)
Exemplo n.º 48
0
    def __getattr__(self, key):
        """Get attributes.

        Interfaces aren't fully returned when the API call is made -
        Published Services aren't returned. Often this doesn't matter,
        so we don't automatically pull this information. However, if you ask
        for the services, this function will go and get the requested
        information on demand. This allows saving of API calls (we don't
        request this unless you're accessing Published Services), but also
        you can treat the object as if the services are there all along. We'll
        get the info when you ask for it, and you can move along like it was
        there from the start.

        If you're doing anything other than asking for services, then this
        passes the call upstream to do the default stuff.
        """
        if key == 'services':
            api = ApiClient()
            services_json = json.loads(api.rest(self.url))
            self.services = PublishedServices(services_json["services"],
                                              self.url)
            return self.services

        return super(Interface, self).__getattr__(key)
Exemplo n.º 49
0
 def delete(self):
     """Delete a service. Warning: Cannot be undone."""
     Utils.info('Deleting published service: ' + str(self.id))
     api = ApiClient()
     response = api.rest(self.url, {}, 'DELETE')
     return response
Exemplo n.º 50
0
 def delete(self):
     """Delete a service. Cannot be undone!"""
     Utils.info('Deleting published service: ' + str(self.id))
     api = ApiClient()
     response = api.rest(self.url, {}, 'DELETE')
     return response
Exemplo n.º 51
0
 def delete(self):
     """Delete the group."""
     Utils.info('Deleting group: ' + str(self.id) + ' (' + self.name + ')')
     api = ApiClient()
     response = api.rest(self.url_v1, {}, 'DELETE')
     return response