def get_loadbalancer(self, datacenter_id, loadbalancer_id):
        """
        Retrieves a single load balancer by ID.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer_id: The unique ID of the load balancer.
        :type       loadbalancer_id: ``str``

        """
        response = self._perform_request(
            '/datacenters/%s/loadbalancers/%s' % (
                datacenter_id, loadbalancer_id))

        return response

def get_loadbalancer ( self , datacenter_id , loadbalancer_id ) : response = self . _perform_request ( '/datacenters/%s/loadbalancers/%s' % ( datacenter_id , loadbalancer_id ) ) return response

Retrieves a single load balancer by ID .


def list_loadbalancers(self, datacenter_id, depth=1):
        """
        Retrieves a list of load balancers in the data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/loadbalancers?depth=%s' % (
                datacenter_id, str(depth)))

        return response

Retrieves a list of load balancers in the data center .


def delete_loadbalancer(self, datacenter_id, loadbalancer_id):
        """
        Removes the load balancer from the data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer_id: The unique ID of the load balancer.
        :type       loadbalancer_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/loadbalancers/%s' % (
                datacenter_id, loadbalancer_id), method='DELETE')

        return response

def delete_loadbalancer ( self , datacenter_id , loadbalancer_id ) : response = self . _perform_request ( url = '/datacenters/%s/loadbalancers/%s' % ( datacenter_id , loadbalancer_id ) , method = 'DELETE' ) return response

Removes the load balancer from the data center .


def create_loadbalancer(self, datacenter_id, loadbalancer):
        """
        Creates a load balancer within the specified data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer: The load balancer object to be created.
        :type       loadbalancer: ``dict``

        """
        data = json.dumps(self._create_loadbalancer_dict(loadbalancer))

        response = self._perform_request(
            url='/datacenters/%s/loadbalancers' % datacenter_id,
            method='POST',
            data=data)

        return response

def create_loadbalancer ( self , datacenter_id , loadbalancer ) : data = json . dumps ( self . _create_loadbalancer_dict ( loadbalancer ) ) response = self . _perform_request ( url = '/datacenters/%s/loadbalancers' % datacenter_id , method = 'POST' , data = data ) return response

Creates a load balancer within the specified data center .


def update_loadbalancer(self, datacenter_id,
                            loadbalancer_id, **kwargs):
        """
        Updates a load balancer

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer_id: The unique ID of the load balancer.
        :type       loadbalancer_id: ``str``

        """
        data = {}

        for attr, value in kwargs.items():
            data[self._underscore_to_camelcase(attr)] = value

        response = self._perform_request(
            url='/datacenters/%s/loadbalancers/%s' % (datacenter_id,
                                                      loadbalancer_id),
            method='PATCH',
            data=json.dumps(data))

        return response

def update_loadbalancer ( self , datacenter_id , loadbalancer_id , * * kwargs ) : data = { } for attr , value in kwargs . items ( ) : data [ self . _underscore_to_camelcase ( attr ) ] = value response = self . _perform_request ( url = '/datacenters/%s/loadbalancers/%s' % ( datacenter_id , loadbalancer_id ) , method = 'PATCH' , data = json . dumps ( data ) ) return response


def get_loadbalancer_members(self, datacenter_id, loadbalancer_id,
                                 depth=1):
        """
        Retrieves the list of NICs that are associated with a load balancer.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer_id: The unique ID of the load balancer.
        :type       loadbalancer_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/loadbalancers/%s/balancednics?depth=%s' % (
                datacenter_id, loadbalancer_id, str(depth)))

        return response

Retrieves the list of NICs that are associated with a load balancer .


def add_loadbalanced_nics(self, datacenter_id,
                              loadbalancer_id, nic_id):
        """
        Associates a NIC with the given load balancer.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer_id: The unique ID of the load balancer.
        :type       loadbalancer_id: ``str``

        :param      nic_id: The ID of the NIC.
        :type       nic_id: ``str``

        """
        data = '{ "id": "' + nic_id + '" }'

        response = self._perform_request(
            url='/datacenters/%s/loadbalancers/%s/balancednics' % (
                datacenter_id,
                loadbalancer_id),
            method='POST',
            data=data)

        return response

Associates a NIC with the given load balancer .


def get_loadbalanced_nic(self, datacenter_id,
                             loadbalancer_id, nic_id, depth=1):
        """
        Gets the properties of a load balanced NIC.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer_id: The unique ID of the load balancer.
        :type       loadbalancer_id: ``str``

        :param      nic_id: The unique ID of the NIC.
        :type       nic_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/loadbalancers/%s/balancednics/%s?depth=%s' % (
                datacenter_id,
                loadbalancer_id,
                nic_id,
                str(depth)))

        return response

Gets the properties of a load balanced NIC .


def remove_loadbalanced_nic(self, datacenter_id,
                                loadbalancer_id, nic_id):
        """
        Removes a NIC from the load balancer.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer_id: The unique ID of the load balancer.
        :type       loadbalancer_id: ``str``

        :param      nic_id: The unique ID of the NIC.
        :type       nic_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/loadbalancers/%s/balancednics/%s' % (
                datacenter_id,
                loadbalancer_id,
                nic_id),
            method='DELETE')

        return response


def get_location(self, location_id, depth=0):
        """
        Retrieves a single location by ID.

        :param      location_id: The unique ID of the location.
        :type       location_id: ``str``

        """
        response = self._perform_request('/locations/%s?depth=%s' % (location_id, depth))
        return response

def get_location ( self , location_id , depth = 0 ) : response = self . _perform_request ( '/locations/%s?depth=%s' % ( location_id , depth ) ) return response


def get_nic(self, datacenter_id, server_id, nic_id, depth=1):
        """
        Retrieves a NIC by its ID.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      nic_id: The unique ID of the NIC.
        :type       nic_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/servers/%s/nics/%s?depth=%s' % (
                datacenter_id,
                server_id,
                nic_id,
                str(depth)))

        return response


def list_nics(self, datacenter_id, server_id, depth=1):
        """
        Retrieves a list of all NICs bound to the specified server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/servers/%s/nics?depth=%s' % (
                datacenter_id,
                server_id,
                str(depth)))

        return response

Retrieves a list of all NICs bound to the specified server .


def delete_nic(self, datacenter_id, server_id, nic_id):
        """
        Removes a NIC from the server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      nic_id: The unique ID of the NIC.
        :type       nic_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/servers/%s/nics/%s' % (
                datacenter_id,
                server_id,
                nic_id),
            method='DELETE')

        return response

def delete_nic ( self , datacenter_id , server_id , nic_id ) : response = self . _perform_request ( url = '/datacenters/%s/servers/%s/nics/%s' % ( datacenter_id , server_id , nic_id ) , method = 'DELETE' ) return response


def create_nic(self, datacenter_id, server_id, nic):
        """
        Creates a NIC on the specified server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      nic: A NIC dict.
        :type       nic: ``dict``

        """

        data = json.dumps(self._create_nic_dict(nic))

        response = self._perform_request(
            url='/datacenters/%s/servers/%s/nics' % (
                datacenter_id,
                server_id),
            method='POST',
            data=data)

        return response

def create_nic ( self , datacenter_id , server_id , nic ) : data = json . dumps ( self . _create_nic_dict ( nic ) ) response = self . _perform_request ( url = '/datacenters/%s/servers/%s/nics' % ( datacenter_id , server_id ) , method = 'POST' , data = data ) return response


def update_nic(self, datacenter_id, server_id,
                   nic_id, **kwargs):
        """
        Updates a NIC with the parameters provided.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      nic_id: The unique ID of the NIC.
        :type       nic_id: ``str``

        """
        data = {}

        for attr, value in kwargs.items():
            data[self._underscore_to_camelcase(attr)] = value

        response = self._perform_request(
            url='/datacenters/%s/servers/%s/nics/%s' % (
                datacenter_id,
                server_id,
                nic_id),
            method='PATCH',
            data=json.dumps(data))

        return response

def update_nic ( self , datacenter_id , server_id , nic_id , * * kwargs ) : data = { } for attr , value in kwargs . items ( ) : data [ self . _underscore_to_camelcase ( attr ) ] = value response = self . _perform_request ( url = '/datacenters/%s/servers/%s/nics/%s' % ( datacenter_id , server_id , nic_id ) , method = 'PATCH' , data = json . dumps ( data ) ) return response

Updates a NIC with the parameters provided .


def get_request(self, request_id, status=False):
        """
        Retrieves a single request by ID.

        :param      request_id: The unique ID of the request.
        :type       request_id: ``str``

        :param      status: Retreive the full status of the request.
        :type       status: ``bool``

        """
        if status:
            response = self._perform_request(
                '/requests/' + request_id + '/status')
        else:
            response = self._perform_request(
                '/requests/%s' % request_id)

        return response

def get_request ( self , request_id , status = False ) : if status : response = self . _perform_request ( '/requests/' + request_id + '/status' ) else : response = self . _perform_request ( '/requests/%s' % request_id ) return response


def get_server(self, datacenter_id, server_id, depth=1):
        """
        Retrieves a server by its ID.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/servers/%s?depth=%s' % (
                datacenter_id,
                server_id,
                str(depth)))

        return response

def get_server ( self , datacenter_id , server_id , depth = 1 ) : response = self . _perform_request ( '/datacenters/%s/servers/%s?depth=%s' % ( datacenter_id , server_id , str ( depth ) ) ) return response


def list_servers(self, datacenter_id, depth=1):
        """
        Retrieves a list of all servers bound to the specified data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/servers?depth=%s' % (datacenter_id, str(depth)))

        return response

def list_servers ( self , datacenter_id , depth = 1 ) : response = self . _perform_request ( '/datacenters/%s/servers?depth=%s' % ( datacenter_id , str ( depth ) ) ) return response

Retrieves a list of all servers bound to the specified data center .


def delete_server(self, datacenter_id, server_id):
        """
        Removes the server from your data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/servers/%s' % (
                datacenter_id,
                server_id),
            method='DELETE')

        return response

def delete_server ( self , datacenter_id , server_id ) : response = self . _perform_request ( url = '/datacenters/%s/servers/%s' % ( datacenter_id , server_id ) , method = 'DELETE' ) return response

Removes the server from your data center .


def create_server(self, datacenter_id, server):
        """
        Creates a server within the data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server: A dict of the server to be created.
        :type       server: ``dict``

        """

        data = json.dumps(self._create_server_dict(server))

        response = self._perform_request(
            url='/datacenters/%s/servers' % (datacenter_id),
            method='POST',
            data=data)

        return response

def create_server ( self , datacenter_id , server ) : data = json . dumps ( self . _create_server_dict ( server ) ) response = self . _perform_request ( url = '/datacenters/%s/servers' % ( datacenter_id ) , method = 'POST' , data = data ) return response

Creates a server within the data center .


def update_server(self, datacenter_id, server_id, **kwargs):
        """
        Updates a server with the parameters provided.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        """
        data = {}

        for attr, value in kwargs.items():
            if attr == 'boot_volume':
                boot_volume_properties = {
                    "id": value
                }
                boot_volume_entities = {
                    "bootVolume": boot_volume_properties
                }
                data.update(boot_volume_entities)
            else:
                data[self._underscore_to_camelcase(attr)] = value

        response = self._perform_request(
            url='/datacenters/%s/servers/%s' % (
                datacenter_id,
                server_id),
            method='PATCH',
            data=json.dumps(data))

        return response

def update_server ( self , datacenter_id , server_id , * * kwargs ) : data = { } for attr , value in kwargs . items ( ) : if attr == 'boot_volume' : boot_volume_properties = { "id" : value } boot_volume_entities = { "bootVolume" : boot_volume_properties } data . update ( boot_volume_entities ) else : data [ self . _underscore_to_camelcase ( attr ) ] = value response = self . _perform_request ( url = '/datacenters/%s/servers/%s' % ( datacenter_id , server_id ) , method = 'PATCH' , data = json . dumps ( data ) ) return response

Updates a server with the parameters provided .


def get_attached_volumes(self, datacenter_id, server_id, depth=1):
        """
        Retrieves a list of volumes attached to the server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/servers/%s/volumes?depth=%s' % (
                datacenter_id,
                server_id,
                str(depth)))

        return response

Retrieves a list of volumes attached to the server .


def get_attached_volume(self, datacenter_id, server_id, volume_id):
        """
        Retrieves volume information.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      volume_id: The unique ID of the volume.
        :type       volume_id: ``str``

        """
        response = self._perform_request(
            '/datacenters/%s/servers/%s/volumes/%s' % (
                datacenter_id,
                server_id,
                volume_id))

        return response

def get_attached_volume ( self , datacenter_id , server_id , volume_id ) : response = self . _perform_request ( '/datacenters/%s/servers/%s/volumes/%s' % ( datacenter_id , server_id , volume_id ) ) return response


def attach_volume(self, datacenter_id, server_id, volume_id):
        """
        Attaches a volume to a server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      volume_id: The unique ID of the volume.
        :type       volume_id: ``str``

        """
        data = '{ "id": "' + volume_id + '" }'

        response = self._perform_request(
            url='/datacenters/%s/servers/%s/volumes' % (
                datacenter_id,
                server_id),
            method='POST',
            data=data)

        return response

def
attach_volume
(
self
,
datacenter_id
,
server_id
,
volume_id
)
:
data
=
'{ "id": "'
+
volume_id
+
'" }'
response
=
self
.
_perform_request
(
url
=
'/datacenters/%s/servers/%s/volumes'
%
(
datacenter_id
,
server_id
)
,
method
=
'POST'
,
data
=
data
)
return
response


def get_attached_cdroms(self, datacenter_id, server_id, depth=1):
        """
        Retrieves a list of CDROMs attached to the server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/servers/%s/cdroms?depth=%s' % (
                datacenter_id,
                server_id,
                str(depth)))

        return response

Retrieves a list of CDROMs attached to the server .


def get_attached_cdrom(self, datacenter_id, server_id, cdrom_id):
        """
        Retrieves an attached CDROM.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      cdrom_id: The unique ID of the CDROM.
        :type       cdrom_id: ``str``

        """
        response = self._perform_request(
            '/datacenters/%s/servers/%s/cdroms/%s' % (
                datacenter_id,
                server_id,
                cdrom_id))

        return response

def get_attached_cdrom ( self , datacenter_id , server_id , cdrom_id ) : response = self . _perform_request ( '/datacenters/%s/servers/%s/cdroms/%s' % ( datacenter_id , server_id , cdrom_id ) ) return response


def attach_cdrom(self, datacenter_id, server_id, cdrom_id):
        """
        Attaches a CDROM to a server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      cdrom_id: The unique ID of the CDROM.
        :type       cdrom_id: ``str``

        """
        data = '{ "id": "' + cdrom_id + '" }'

        response = self._perform_request(
            url='/datacenters/%s/servers/%s/cdroms' % (
                datacenter_id,
                server_id),
            method='POST',
            data=data)

        return response

def
attach_cdrom
(
self
,
datacenter_id
,
server_id
,
cdrom_id
)
:
data
=
'{ "id": "'
+
cdrom_id
+
'" }'
response
=
self
.
_perform_request
(
url
=
'/datacenters/%s/servers/%s/cdroms'
%
(
datacenter_id
,
server_id
)
,
method
=
'POST'
,
data
=
data
)
return
response


def start_server(self, datacenter_id, server_id):
        """
        Starts the server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/servers/%s/start' % (
                datacenter_id,
                server_id),
            method='POST-ACTION')

        return response

def start_server ( self , datacenter_id , server_id ) : response = self . _perform_request ( url = '/datacenters/%s/servers/%s/start' % ( datacenter_id , server_id ) , method = 'POST-ACTION' ) return response


def stop_server(self, datacenter_id, server_id):
        """
        Stops the server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/servers/%s/stop' % (
                datacenter_id,
                server_id),
            method='POST-ACTION')

        return response

def stop_server ( self , datacenter_id , server_id ) : response = self . _perform_request ( url = '/datacenters/%s/servers/%s/stop' % ( datacenter_id , server_id ) , method = 'POST-ACTION' ) return response


def reboot_server(self, datacenter_id, server_id):
        """
        Reboots the server.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/servers/%s/reboot' % (
                datacenter_id,
                server_id),
            method='POST-ACTION')

        return response

def reboot_server ( self , datacenter_id , server_id ) : response = self . _perform_request ( url = '/datacenters/%s/servers/%s/reboot' % ( datacenter_id , server_id ) , method = 'POST-ACTION' ) return response


def create_snapshot(self, datacenter_id, volume_id,
                        name=None, description=None):
        """
        Creates a snapshot of the specified volume.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      volume_id: The unique ID of the volume.
        :type       volume_id: ``str``

        :param      name: The name given to the volume.
        :type       name: ``str``

        :param      description: The description given to the volume.
        :type       description: ``str``

        """

        data = {'name': name, 'description': description}

        response = self._perform_request(
            '/datacenters/%s/volumes/%s/create-snapshot' % (
                datacenter_id, volume_id),
            method='POST-ACTION-JSON',
            data=urlencode(data))

        return response

Creates a snapshot of the specified volume .


def restore_snapshot(self, datacenter_id, volume_id, snapshot_id):
        """
        Restores a snapshot to the specified volume.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      volume_id: The unique ID of the volume.
        :type       volume_id: ``str``

        :param      snapshot_id: The unique ID of the snapshot.
        :type       snapshot_id: ``str``

        """
        data = {'snapshotId': snapshot_id}

        response = self._perform_request(
            url='/datacenters/%s/volumes/%s/restore-snapshot' % (
                datacenter_id,
                volume_id),
            method='POST-ACTION',
            data=urlencode(data))

        return response

Restores a snapshot to the specified volume .


def remove_snapshot(self, snapshot_id):
        """
        Removes a snapshot.

        :param      snapshot_id: The ID of the snapshot
                                 you wish to remove.
        :type       snapshot_id: ``str``

        """
        response = self._perform_request(
            url='/snapshots/' + snapshot_id, method='DELETE')

        return response

def remove_snapshot ( self , snapshot_id ) : response = self . _perform_request ( url = '/snapshots/' + snapshot_id , method = 'DELETE' ) return response


def get_group(self, group_id, depth=1):
        """
        Retrieves a single group by ID.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/um/groups/%s?depth=%s' % (group_id, str(depth)))

        return response

def get_group ( self , group_id , depth = 1 ) : response = self . _perform_request ( '/um/groups/%s?depth=%s' % ( group_id , str ( depth ) ) ) return response


def create_group(self, group):
        """
        Creates a new group and set group privileges.

        :param      group: The group object to be created.
        :type       group: ``dict``

        """
        data = json.dumps(self._create_group_dict(group))

        response = self._perform_request(
            url='/um/groups',
            method='POST',
            data=data)

        return response

def create_group ( self , group ) : data = json . dumps ( self . _create_group_dict ( group ) ) response = self . _perform_request ( url = '/um/groups' , method = 'POST' , data = data ) return response

Creates a new group and set group privileges .


def update_group(self, group_id, **kwargs):
        """
        Updates a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        """
        properties = {}

        # make the key camel-case transformable
        if 'create_datacenter' in kwargs:
            kwargs['create_data_center'] = kwargs.pop('create_datacenter')

        for attr, value in kwargs.items():
            properties[self._underscore_to_camelcase(attr)] = value

        data = {
            "properties": properties
        }

        response = self._perform_request(
            url='/um/groups/%s' % group_id,
            method='PUT',
            data=json.dumps(data))

        return response

def
update_group
(
self
,
group_id
,
*
*
kwargs
)
:
properties
=
{
}
# make the key camel-case transformable
if
'create_datacenter'
in
kwargs
:
kwargs
[
'create_data_center'
]
=
kwargs
.
pop
(
'create_datacenter'
)
for
attr
,
value
in
kwargs
.
items
(
)
:
properties
[
self
.
_underscore_to_camelcase
(
attr
)
]
=
value
data
=
{
"properties"
:
properties
}
response
=
self
.
_perform_request
(
url
=
'/um/groups/%s'
%
group_id
,
method
=
'PUT'
,
data
=
json
.
dumps
(
data
)
)
return
response


def delete_group(self, group_id):
        """
        Removes a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        """
        response = self._perform_request(
            url='/um/groups/%s' % group_id,
            method='DELETE')

        return response

def delete_group ( self , group_id ) : response = self . _perform_request ( url = '/um/groups/%s' % group_id , method = 'DELETE' ) return response


def list_shares(self, group_id, depth=1):
        """
        Retrieves a list of all shares though a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/um/groups/%s/shares?depth=%s' % (group_id, str(depth)))

        return response

def list_shares ( self , group_id , depth = 1 ) : response = self . _perform_request ( '/um/groups/%s/shares?depth=%s' % ( group_id , str ( depth ) ) ) return response

Retrieves a list of all shares though a group .


def get_share(self, group_id, resource_id, depth=1):
        """
        Retrieves a specific resource share available to a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      resource_id: The unique ID of the resource.
        :type       resource_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/um/groups/%s/shares/%s?depth=%s'
            % (group_id, resource_id, str(depth)))

        return response

def get_share ( self , group_id , resource_id , depth = 1 ) : response = self . _perform_request ( '/um/groups/%s/shares/%s?depth=%s' % ( group_id , resource_id , str ( depth ) ) ) return response

Retrieves a specific resource share available to a group .


def add_share(self, group_id, resource_id, **kwargs):
        """
        Shares a resource through a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      resource_id: The unique ID of the resource.
        :type       resource_id: ``str``

        """
        properties = {}

        for attr, value in kwargs.items():
            properties[self._underscore_to_camelcase(attr)] = value

        data = {
            "properties": properties
        }

        response = self._perform_request(
            url='/um/groups/%s/shares/%s' % (group_id, resource_id),
            method='POST',
            data=json.dumps(data))

        return response

def add_share ( self , group_id , resource_id , * * kwargs ) : properties = { } for attr , value in kwargs . items ( ) : properties [ self . _underscore_to_camelcase ( attr ) ] = value data = { "properties" : properties } response = self . _perform_request ( url = '/um/groups/%s/shares/%s' % ( group_id , resource_id ) , method = 'POST' , data = json . dumps ( data ) ) return response


def delete_share(self, group_id, resource_id):
        """
        Removes a resource share from a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      resource_id: The unique ID of the resource.
        :type       resource_id: ``str``

        """
        response = self._perform_request(
            url='/um/groups/%s/shares/%s' % (group_id, resource_id),
            method='DELETE')

        return response

def delete_share ( self , group_id , resource_id ) : response = self . _perform_request ( url = '/um/groups/%s/shares/%s' % ( group_id , resource_id ) , method = 'DELETE' ) return response


def get_user(self, user_id, depth=1):
        """
        Retrieves a single user by ID.

        :param      user_id: The unique ID of the user.
        :type       user_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/um/users/%s?depth=%s' % (user_id, str(depth)))

        return response

def get_user ( self , user_id , depth = 1 ) : response = self . _perform_request ( '/um/users/%s?depth=%s' % ( user_id , str ( depth ) ) ) return response


def create_user(self, user):
        """
        Creates a new user.

        :param      user: The user object to be created.
        :type       user: ``dict``

        """
        data = self._create_user_dict(user=user)

        response = self._perform_request(
            url='/um/users',
            method='POST',
            data=json.dumps(data))

        return response

def create_user ( self , user ) : data = self . _create_user_dict ( user = user ) response = self . _perform_request ( url = '/um/users' , method = 'POST' , data = json . dumps ( data ) ) return response


def update_user(self, user_id, **kwargs):
        """
        Updates a user.

        :param      user_id: The unique ID of the user.
        :type       user_id: ``str``

        """
        properties = {}

        for attr, value in kwargs.items():
            properties[self._underscore_to_camelcase(attr)] = value

        data = {
            "properties": properties
        }

        response = self._perform_request(
            url='/um/users/%s' % user_id,
            method='PUT',
            data=json.dumps(data))

        return response

def update_user ( self , user_id , * * kwargs ) : properties = { } for attr , value in kwargs . items ( ) : properties [ self . _underscore_to_camelcase ( attr ) ] = value data = { "properties" : properties } response = self . _perform_request ( url = '/um/users/%s' % user_id , method = 'PUT' , data = json . dumps ( data ) ) return response


def delete_user(self, user_id):
        """
        Removes a user.

        :param      user_id: The unique ID of the user.
        :type       user_id: ``str``

        """
        response = self._perform_request(
            url='/um/users/%s' % user_id,
            method='DELETE')

        return response

def delete_user ( self , user_id ) : response = self . _perform_request ( url = '/um/users/%s' % user_id , method = 'DELETE' ) return response


def list_group_users(self, group_id, depth=1):
        """
        Retrieves a list of all users that are members of a particular group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/um/groups/%s/users?depth=%s' % (group_id, str(depth)))

        return response

def list_group_users ( self , group_id , depth = 1 ) : response = self . _perform_request ( '/um/groups/%s/users?depth=%s' % ( group_id , str ( depth ) ) ) return response

Retrieves a list of all users that are members of a particular group .


def add_group_user(self, group_id, user_id):
        """
        Adds an existing user to a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      user_id: The unique ID of the user.
        :type       user_id: ``str``

        """
        data = {
            "id": user_id
        }

        response = self._perform_request(
            url='/um/groups/%s/users' % group_id,
            method='POST',
            data=json.dumps(data))

        return response

def add_group_user ( self , group_id , user_id ) : data = { "id" : user_id } response = self . _perform_request ( url = '/um/groups/%s/users' % group_id , method = 'POST' , data = json . dumps ( data ) ) return response


def remove_group_user(self, group_id, user_id):
        """
        Removes a user from a group.

        :param      group_id: The unique ID of the group.
        :type       group_id: ``str``

        :param      user_id: The unique ID of the user.
        :type       user_id: ``str``

        """
        response = self._perform_request(
            url='/um/groups/%s/users/%s' % (group_id, user_id),
            method='DELETE')

        return response

def remove_group_user ( self , group_id , user_id ) : response = self . _perform_request ( url = '/um/groups/%s/users/%s' % ( group_id , user_id ) , method = 'DELETE' ) return response


def list_resources(self, resource_type=None, depth=1):
        """
        Retrieves a list of all resources.

        :param      resource_type: The resource type: datacenter, image,
                                   snapshot or ipblock. Default is None,
                                   i.e., all resources are listed.
        :type       resource_type: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        if resource_type is not None:
            response = self._perform_request(
                '/um/resources/%s?depth=%s' % (resource_type, str(depth)))
        else:
            response = self._perform_request(
                '/um/resources?depth=' + str(depth))

        return response

def list_resources ( self , resource_type = None , depth = 1 ) : if resource_type is not None : response = self . _perform_request ( '/um/resources/%s?depth=%s' % ( resource_type , str ( depth ) ) ) else : response = self . _perform_request ( '/um/resources?depth=' + str ( depth ) ) return response


def get_resource(self, resource_type, resource_id, depth=1):
        """
        Retrieves a single resource of a particular type.

        :param      resource_type: The resource type: datacenter, image,
                                   snapshot or ipblock.
        :type       resource_type: ``str``

        :param      resource_id: The unique ID of the resource.
        :type       resource_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/um/resources/%s/%s?depth=%s' % (
                resource_type, resource_id, str(depth)))

        return response

def get_resource ( self , resource_type , resource_id , depth = 1 ) : response = self . _perform_request ( '/um/resources/%s/%s?depth=%s' % ( resource_type , resource_id , str ( depth ) ) ) return response

Retrieves a single resource of a particular type .


def get_volume(self, datacenter_id, volume_id):
        """
        Retrieves a single volume by ID.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      volume_id: The unique ID of the volume.
        :type       volume_id: ``str``

        """
        response = self._perform_request(
            '/datacenters/%s/volumes/%s' % (datacenter_id, volume_id))

        return response

def get_volume ( self , datacenter_id , volume_id ) : response = self . _perform_request ( '/datacenters/%s/volumes/%s' % ( datacenter_id , volume_id ) ) return response


def list_volumes(self, datacenter_id, depth=1):
        """
        Retrieves a list of volumes in the data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        response = self._perform_request(
            '/datacenters/%s/volumes?depth=%s' % (datacenter_id, str(depth)))

        return response

def list_volumes ( self , datacenter_id , depth = 1 ) : response = self . _perform_request ( '/datacenters/%s/volumes?depth=%s' % ( datacenter_id , str ( depth ) ) ) return response

Retrieves a list of volumes in the data center .


def delete_volume(self, datacenter_id, volume_id):
        """
        Removes a volume from the data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      volume_id: The unique ID of the volume.
        :type       volume_id: ``str``

        """
        response = self._perform_request(
            url='/datacenters/%s/volumes/%s' % (
                datacenter_id, volume_id), method='DELETE')

        return response

def delete_volume ( self , datacenter_id , volume_id ) : response = self . _perform_request ( url = '/datacenters/%s/volumes/%s' % ( datacenter_id , volume_id ) , method = 'DELETE' ) return response


def create_volume(self, datacenter_id, volume):
        """
        Creates a volume within the specified data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      volume: A volume dict.
        :type       volume: ``dict``

        """

        data = (json.dumps(self._create_volume_dict(volume)))

        response = self._perform_request(
            url='/datacenters/%s/volumes' % datacenter_id,
            method='POST',
            data=data)

        return response

def create_volume ( self , datacenter_id , volume ) : data = ( json . dumps ( self . _create_volume_dict ( volume ) ) ) response = self . _perform_request ( url = '/datacenters/%s/volumes' % datacenter_id , method = 'POST' , data = data ) return response

Creates a volume within the specified data center .


def wait_for_completion(self, response, timeout=3600, initial_wait=5, scaleup=10):
        """
        Poll resource request status until resource is provisioned.

        :param      response: A response dict, which needs to have a 'requestId' item.
        :type       response: ``dict``

        :param      timeout: Maximum waiting time in seconds. None means infinite waiting time.
        :type       timeout: ``int``

        :param      initial_wait: Initial polling interval in seconds.
        :type       initial_wait: ``int``

        :param      scaleup: Double polling interval every scaleup steps, which will be doubled.
        :type       scaleup: ``int``

        """
        if not response:
            return
        logger = logging.getLogger(__name__)
        wait_period = initial_wait
        next_increase = time.time() + wait_period * scaleup
        if timeout:
            timeout = time.time() + timeout
        while True:
            request = self.get_request(request_id=response['requestId'], status=True)

            if request['metadata']['status'] == 'DONE':
                break
            elif request['metadata']['status'] == 'FAILED':
                raise PBFailedRequest(
                    'Request {0} failed to complete: {1}'.format(
                        response['requestId'], request['metadata']['message']),
                    response['requestId']
                )

            current_time = time.time()
            if timeout and current_time > timeout:
                raise PBTimeoutError('Timed out waiting for request {0}.'.format(
                    response['requestId']), response['requestId'])

            if current_time > next_increase:
                wait_period *= 2
                next_increase = time.time() + wait_period * scaleup
                scaleup *= 2

            logger.info("Request %s is in state '%s'. Sleeping for %i seconds...",
                        response['requestId'], request['metadata']['status'], wait_period)
            time.sleep(wait_period)

Poll resource request status until resource is provisioned .


def _b(s, encoding='utf-8'):
        """
        Returns the given string as a string of bytes. That means in
        Python2 as a str object, and in Python3 as a bytes object.
        Raises a TypeError, if it cannot be converted.
        """
        if six.PY2:
            # This is Python2
            if isinstance(s, str):
                return s
            elif isinstance(s, unicode):  # noqa, pylint: disable=undefined-variable
                return s.encode(encoding)
        else:
            # And this is Python3
            if isinstance(s, bytes):
                return s
            elif isinstance(s, str):
                return s.encode(encoding)

        raise TypeError("Invalid argument %r for _b()" % (s,))

Returns the given string as a string of bytes . That means in Python2 as a str object and in Python3 as a bytes object . Raises a TypeError if it cannot be converted .


def _underscore_to_camelcase(value):
        """
        Convert Python snake case back to mixed case.
        """
        def camelcase():
            yield str.lower
            while True:
                yield str.capitalize

        c = camelcase()
        return "".join(next(c)(x) if x else '_' for x in value.split("_"))

def _underscore_to_camelcase ( value ) : def camelcase ( ) : yield str . lower while True : yield str . capitalize c = camelcase ( ) return "" . join ( next ( c ) ( x ) if x else '_' for x in value . split ( "_" ) )

Convert Python snake case back to mixed case .


def find_item_by_name(list_, namegetter, name):
    """
    Find a item a given list by a matching name.

    The search for the name is done in this relaxing way:

    - exact name match
    - case-insentive name match
    - attribute starts with the name
    - attribute starts with the name (case insensitive)
    - name appears in the attribute
    - name appears in the attribute (case insensitive)

    :param    list_: A list of elements
    :type     list_: ``list``

    :param    namegetter: Function that returns the name for a given
                          element in the list
    :type     namegetter: ``function``

    :param    name: Name to search for
    :type     name: ``str``

    """
    matching_items = [i for i in list_ if namegetter(i) == name]
    if not matching_items:
        prog = re.compile(re.escape(name) + '$', re.IGNORECASE)
        matching_items = [i for i in list_ if prog.match(namegetter(i))]
    if not matching_items:
        prog = re.compile(re.escape(name))
        matching_items = [i for i in list_ if prog.match(namegetter(i))]
    if not matching_items:
        prog = re.compile(re.escape(name), re.IGNORECASE)
        matching_items = [i for i in list_ if prog.match(namegetter(i))]
    if not matching_items:
        prog = re.compile(re.escape(name))
        matching_items = [i for i in list_ if prog.search(namegetter(i))]
    if not matching_items:
        prog = re.compile(re.escape(name), re.IGNORECASE)
        matching_items = [i for i in list_ if prog.search(namegetter(i))]
    return matching_items

def find_item_by_name ( list_ , namegetter , name ) : matching_items = [ i for i in list_ if namegetter ( i ) == name ] if not matching_items : prog = re . compile ( re . escape ( name ) + '$' , re . IGNORECASE ) matching_items = [ i for i in list_ if prog . match ( namegetter ( i ) ) ] if not matching_items : prog = re . compile ( re . escape ( name ) ) matching_items = [ i for i in list_ if prog . match ( namegetter ( i ) ) ] if not matching_items : prog = re . compile ( re . escape ( name ) , re . IGNORECASE ) matching_items = [ i for i in list_ if prog . match ( namegetter ( i ) ) ] if not matching_items : prog = re . compile ( re . escape ( name ) ) matching_items = [ i for i in list_ if prog . search ( namegetter ( i ) ) ] if not matching_items : prog = re . compile ( re . escape ( name ) , re . IGNORECASE ) matching_items = [ i for i in list_ if prog . search ( namegetter ( i ) ) ] return matching_items

Find a item a given list by a matching name .


def getServerInfo(pbclient=None, dc_id=None):
    ''' gets info of servers of a data center'''
    if pbclient is None:
        raise ValueError("argument 'pbclient' must not be None")
    if dc_id is None:
        raise ValueError("argument 'dc_id' must not be None")
    # list of all found server's info
    server_info = []
    # depth 1 is enough for props/meta
    servers = pbclient.list_servers(dc_id, 1)
    for server in servers['items']:
        props = server['properties']
        info = dict(id=server['id'], name=props['name'],
                    state=server['metadata']['state'],
                    vmstate=props['vmState'])
        server_info.append(info)
    # end for(servers)
    return server_info

def
getServerInfo
(
pbclient
=
,
dc_id
=
)
:
if
pbclient
is
:
raise
ValueError
(
"argument 'pbclient' must not be None"
)
if
dc_id
is
:
raise
ValueError
(
"argument 'dc_id' must not be None"
)
# list of all found server's info
server_info
=
[
]
# depth 1 is enough for props/meta
servers
=
pbclient
.
list_servers
(
dc_id
,
1
)
for
server
in
servers
[
'items'
]
:
props
=
server
[
'properties'
]
info
=
dict
(
id
=
server
[
'id'
]
,
name
=
props
[
'name'
]
,
state
=
server
[
'metadata'
]
[
'state'
]
,
vmstate
=
props
[
'vmState'
]
)
server_info
.
append
(
info
)
# end for(servers)
return
server_info


def getServerStates(pbclient=None, dc_id=None, serverid=None, servername=None):
    ''' gets states of a server'''
    if pbclient is None:
        raise ValueError("argument 'pbclient' must not be None")
    if dc_id is None:
        raise ValueError("argument 'dc_id' must not be None")
    server = None
    if serverid is None:
        if servername is None:
            raise ValueError("one of 'serverid' or 'servername' must be specified")
        # so, arg.servername is set (to whatever)
        server_info = select_where(getServerInfo(pbclient, dc_id),
                                   ['id', 'name', 'state', 'vmstate'],
                                   name=servername)
        if len(server_info) > 1:
            raise NameError("ambiguous server name '{}'".format(servername))
        if len(server_info) == 1:
            server = server_info[0]
    else:
        # get by ID may also fail if it's removed
        # in this case, catch exception (message 404) and be quiet for a while
        # unfortunately this has changed from Py2 to Py3
        try:
            server_info = pbclient.get_server(dc_id, serverid, 1)
            server = dict(id=server_info['id'],
                          name=server_info['properties']['name'],
                          state=server_info['metadata']['state'],
                          vmstate=server_info['properties']['vmState'])
        except Exception:
            ex = sys.exc_info()[1]
            if ex.args[0] is not None and ex.args[0] == 404:
                print("Server w/ ID {} not found".format(serverid))
                server = None
            else:
                raise ex
        # end try/except
    # end if/else(serverid)
    return server


def get_self(session, user_details=None):
    """
    Get details about the currently authenticated user
    """
    # Set compact to true
    if user_details:
        user_details['compact'] = True
    response = make_get_request(session, 'self', params_data=user_details)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise SelfNotRetrievedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )

def
get_self
(
session
,
user_details
=
)
:
# Set compact to true
if
user_details
:
user_details
[
'compact'
]
=
True
response
=
make_get_request
(
session
,
'self'
,
params_data
=
user_details
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
SelfNotRetrievedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def get_user_by_id(session, user_id, user_details=None):
    """
    Get details about specific user
    """
    if user_details:
        user_details['compact'] = True
    response = make_get_request(
        session, 'users/{}'.format(user_id), params_data=user_details)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise UserNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )

def get_user_by_id ( session , user_id , user_details = None ) : if user_details : user_details [ 'compact' ] = True response = make_get_request ( session , 'users/{}' . format ( user_id ) , params_data = user_details ) json_data = response . json ( ) if response . status_code == 200 : return json_data [ 'result' ] else : raise UserNotFoundException ( message = json_data [ 'message' ] , error_code = json_data [ 'error_code' ] , request_id = json_data [ 'request_id' ] )


def get_self_user_id(session):
    """
    Get the currently authenticated user ID
    """
    response = make_get_request(session, 'self')
    if response.status_code == 200:
        return response.json()['result']['id']
    else:
        raise UserIdNotRetrievedException(
            'Error retrieving user id: %s' % response.text, response.text)

def
get_self_user_id
(
session
)
:
response
=
make_get_request
(
session
,
'self'
)
if
response
.
status_code
==
200
:
return
response
.
json
(
)
[
'result'
]
[
'id'
]
else
:
raise
UserIdNotRetrievedException
(
'Error retrieving user id: %s'
%
response
.
text
,
response
.
text
)


def add_user_jobs(session, job_ids):
    """
    Add a list of jobs to the currently authenticated user
    """
    jobs_data = {
        'jobs[]': job_ids
    }
    response = make_post_request(session, 'self/jobs', json_data=jobs_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        raise UserJobsNotAddedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])

def add_user_jobs ( session , job_ids ) : jobs_data = { 'jobs[]' : job_ids } response = make_post_request ( session , 'self/jobs' , json_data = jobs_data ) json_data = response . json ( ) if response . status_code == 200 : return json_data [ 'status' ] else : raise UserJobsNotAddedException ( message = json_data [ 'message' ] , error_code = json_data [ 'error_code' ] , request_id = json_data [ 'request_id' ] )


def set_user_jobs(session, job_ids):
    """
    Replace the currently authenticated user's list of jobs with a new list of
    jobs
    """
    jobs_data = {
        'jobs[]': job_ids
    }
    response = make_put_request(session, 'self/jobs', json_data=jobs_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        raise UserJobsNotSetException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])

def set_user_jobs ( session , job_ids ) : jobs_data = { 'jobs[]' : job_ids } response = make_put_request ( session , 'self/jobs' , json_data = jobs_data ) json_data = response . json ( ) if response . status_code == 200 : return json_data [ 'status' ] else : raise UserJobsNotSetException ( message = json_data [ 'message' ] , error_code = json_data [ 'error_code' ] , request_id = json_data [ 'request_id' ] )

Replace the currently authenticated user s list of jobs with a new list of jobs


def delete_user_jobs(session, job_ids):
    """
    Remove a list of jobs from the currently authenticated user
    """
    jobs_data = {
        'jobs[]': job_ids
    }
    response = make_delete_request(session, 'self/jobs', json_data=jobs_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        raise UserJobsNotDeletedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])

def delete_user_jobs ( session , job_ids ) : jobs_data = { 'jobs[]' : job_ids } response = make_delete_request ( session , 'self/jobs' , json_data = jobs_data ) json_data = response . json ( ) if response . status_code == 200 : return json_data [ 'status' ] else : raise UserJobsNotDeletedException ( message = json_data [ 'message' ] , error_code = json_data [ 'error_code' ] , request_id = json_data [ 'request_id' ] )


def get_users(session, query):
    """
    Get one or more users
    """
    # GET /api/users/0.1/users
    response = make_get_request(session, 'users', params_data=query)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise UsersNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])

def
get_users
(
session
,
query
)
:
# GET /api/users/0.1/users
response
=
make_get_request
(
session
,
'users'
,
params_data
=
query
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
UsersNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def create_project(session, title, description,
                   currency, budget, jobs):
    """
    Create a project
    """
    project_data = {'title': title,
                    'description': description,
                    'currency': currency,
                    'budget': budget,
                    'jobs': jobs
                    }

    # POST /api/projects/0.1/projects/
    response = make_post_request(session, 'projects', json_data=project_data)
    json_data = response.json()
    if response.status_code == 200:
        project_data = json_data['result']
        p = Project(project_data)
        p.url = urljoin(session.url, 'projects/%s' % p.seo_url)
        return p
    else:
        raise ProjectNotCreatedException(message=json_data['message'],
                                         error_code=json_data['error_code'],
                                         request_id=json_data['request_id'],
                                         )

def
create_project
(
session
,
title
,
description
,
currency
,
budget
,
jobs
)
:
project_data
=
{
'title'
:
title
,
'description'
:
description
,
'currency'
:
currency
,
'budget'
:
budget
,
'jobs'
:
jobs
}
# POST /api/projects/0.1/projects/
response
=
make_post_request
(
session
,
'projects'
,
json_data
=
project_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
project_data
=
json_data
[
'result'
]
p
=
Project
(
project_data
)
p
.
url
=
urljoin
(
session
.
url
,
'projects/%s'
%
p
.
seo_url
)
return
p
else
:
raise
ProjectNotCreatedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
,
)


def create_hireme_project(session, title, description,
                          currency, budget, jobs, hireme_initial_bid):
    """
    Create a fixed project
    """
    jobs.append(create_job_object(id=417))  # Hire Me job, required

    project_data = {'title': title,
                    'description': description,
                    'currency': currency,
                    'budget': budget,
                    'jobs': jobs,
                    'hireme': True,
                    'hireme_initial_bid': hireme_initial_bid
                    }

    # POST /api/projects/0.1/projects/
    response = make_post_request(session, 'projects', json_data=project_data)
    json_data = response.json()
    if response.status_code == 200:
        project_data = json_data['result']
        p = Project(project_data)
        p.url = urljoin(session.url, 'projects/%s' % p.seo_url)
        return p
    else:
        raise ProjectNotCreatedException(message=json_data['message'],
                                         error_code=json_data['error_code'],
                                         request_id=json_data['request_id'],
                                         )

def
create_hireme_project
(
session
,
title
,
description
,
currency
,
budget
,
jobs
,
hireme_initial_bid
)
:
jobs
.
append
(
create_job_object
(
id
=
417
)
)
# Hire Me job, required
project_data
=
{
'title'
:
title
,
'description'
:
description
,
'currency'
:
currency
,
'budget'
:
budget
,
'jobs'
:
jobs
,
'hireme'
:
True
,
'hireme_initial_bid'
:
hireme_initial_bid
}
# POST /api/projects/0.1/projects/
response
=
make_post_request
(
session
,
'projects'
,
json_data
=
project_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
project_data
=
json_data
[
'result'
]
p
=
Project
(
project_data
)
p
.
url
=
urljoin
(
session
.
url
,
'projects/%s'
%
p
.
seo_url
)
return
p
else
:
raise
ProjectNotCreatedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
,
)


def get_projects(session, query):
    """
    Get one or more projects
    """
    # GET /api/projects/0.1/projects
    response = make_get_request(session, 'projects', params_data=query)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise ProjectsNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])

def
get_projects
(
session
,
query
)
:
# GET /api/projects/0.1/projects
response
=
make_get_request
(
session
,
'projects'
,
params_data
=
query
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
ProjectsNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def get_project_by_id(session, project_id, project_details=None, user_details=None):
    """
    Get a single project by ID
    """
    # GET /api/projects/0.1/projects/<int:project_id>
    query = {}
    if project_details:
        query.update(project_details)
    if user_details:
        query.update(user_details)
    response = make_get_request(
        session, 'projects/{}'.format(project_id), params_data=query)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise ProjectsNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )


def search_projects(session,
                    query,
                    search_filter=None,
                    project_details=None,
                    user_details=None,
                    limit=10,
                    offset=0,
                    active_only=None):
    """
    Search for all projects
    """
    search_data = {
        'query': query,
        'limit': limit,
        'offset': offset,
    }
    if search_filter:
        search_data.update(search_filter)
    if project_details:
        search_data.update(project_details)
    if user_details:
        search_data.update(user_details)

    # GET /api/projects/0.1/projects/all/
    # GET /api/projects/0.1/projects/active/
    endpoint = 'projects/{}'.format('active' if active_only else 'all')
    response = make_get_request(session, endpoint, params_data=search_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise ProjectsNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])


def place_project_bid(session, project_id, bidder_id, description, amount,
                      period, milestone_percentage):
    """
    Place a bid on a project
    """
    bid_data = {
        'project_id': project_id,
        'bidder_id': bidder_id,
        'description': description,
        'amount': amount,
        'period': period,
        'milestone_percentage': milestone_percentage,
    }
    # POST /api/projects/0.1/bids/
    response = make_post_request(session, 'bids', json_data=bid_data)
    json_data = response.json()
    if response.status_code == 200:
        bid_data = json_data['result']
        return Bid(bid_data)
    else:
        raise BidNotPlacedException(message=json_data['message'],
                                    error_code=json_data['error_code'],
                                    request_id=json_data['request_id'])

def
place_project_bid
(
session
,
project_id
,
bidder_id
,
description
,
amount
,
period
,
milestone_percentage
)
:
bid_data
=
{
'project_id'
:
project_id
,
'bidder_id'
:
bidder_id
,
'description'
:
description
,
'amount'
:
amount
,
'period'
:
period
,
'milestone_percentage'
:
milestone_percentage
,
}
# POST /api/projects/0.1/bids/
response
=
make_post_request
(
session
,
'bids'
,
json_data
=
bid_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
bid_data
=
json_data
[
'result'
]
return
Bid
(
bid_data
)
else
:
raise
BidNotPlacedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0):
    """
    Get the list of bids
    """
    get_bids_data = {}
    if bid_ids:
        get_bids_data['bids[]'] = bid_ids
    if project_ids:
        get_bids_data['projects[]'] = project_ids
    get_bids_data['limit'] = limit
    get_bids_data['offset'] = offset
    # GET /api/projects/0.1/bids/
    response = make_get_request(session, 'bids', params_data=get_bids_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise BidsNotFoundException(
            message=json_data['message'], error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )

def
get_bids
(
session
,
project_ids
=
[
]
,
bid_ids
=
[
]
,
limit
=
10
,
offset
=
0
)
:
get_bids_data
=
{
}
if
bid_ids
:
get_bids_data
[
'bids[]'
]
=
bid_ids
if
project_ids
:
get_bids_data
[
'projects[]'
]
=
project_ids
get_bids_data
[
'limit'
]
=
limit
get_bids_data
[
'offset'
]
=
offset
# GET /api/projects/0.1/bids/
response
=
make_get_request
(
session
,
'bids'
,
params_data
=
get_bids_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
BidsNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def get_milestones(session, project_ids=[], milestone_ids=[], user_details=None, limit=10, offset=0):
    """
    Get the list of milestones
    """
    get_milestones_data = {}
    if milestone_ids:
        get_milestones_data['milestones[]'] = milestone_ids
    if project_ids:
        get_milestones_data['projects[]'] = project_ids
    get_milestones_data['limit'] = limit
    get_milestones_data['offset'] = offset

    # Add projections if they exist
    if user_details:
        get_milestones_data.update(user_details)

    # GET /api/projects/0.1/milestones/

    response = make_get_request(
        session, 'milestones', params_data=get_milestones_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise MilestonesNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )

def
get_milestones
(
session
,
project_ids
=
[
]
,
milestone_ids
=
[
]
,
user_details
=
,
limit
=
10
,
offset
=
0
)
:
get_milestones_data
=
{
}
if
milestone_ids
:
get_milestones_data
[
'milestones[]'
]
=
milestone_ids
if
project_ids
:
get_milestones_data
[
'projects[]'
]
=
project_ids
get_milestones_data
[
'limit'
]
=
limit
get_milestones_data
[
'offset'
]
=
offset
# Add projections if they exist
if
user_details
:
get_milestones_data
.
update
(
user_details
)
# GET /api/projects/0.1/milestones/
response
=
make_get_request
(
session
,
'milestones'
,
params_data
=
get_milestones_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
MilestonesNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def get_milestone_by_id(session, milestone_id, user_details=None):
    """
    Get a specific milestone
    """
    # GET /api/projects/0.1/milestones/{milestone_id}/
    endpoint = 'milestones/{}'.format(milestone_id)

    response = make_get_request(session, endpoint, params_data=user_details)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise MilestonesNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )


def award_project_bid(session, bid_id):
    """
    Award a bid on a project
    """
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    bid_data = {
        'action': 'award'
    }
    # POST /api/projects/0.1/bids/{bid_id}/?action=award
    endpoint = 'bids/{}'.format(bid_id)
    response = make_put_request(session, endpoint, headers=headers,
                                params_data=bid_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        json_data = response.json()
        raise BidNotAwardedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )


def revoke_project_bid(session, bid_id):
    """
    Revoke a bid on a project
    """
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    bid_data = {
        'action': 'revoke'
    }
    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke
    endpoint = 'bids/{}'.format(bid_id)
    response = make_put_request(session, endpoint, headers=headers,
                                params_data=bid_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        json_data = response.json()
        raise BidNotRevokedException(message=json_data['message'],
                                     error_code=json_data['error_code'],
                                     request_id=json_data['request_id'])


def accept_project_bid(session, bid_id):
    """
    Accept a bid on a project
    """
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    bid_data = {
        'action': 'accept'
    }
    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke
    endpoint = 'bids/{}'.format(bid_id)
    response = make_put_request(session, endpoint, headers=headers,
                                params_data=bid_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        json_data = response.json()
        raise BidNotAcceptedException(message=json_data['message'],
                                      error_code=json_data['error_code'],
                                      request_id=json_data['request_id'])


def retract_project_bid(session, bid_id):
    """
    Retract a bid on a project
    """
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    bid_data = {
        'action': 'retract'
    }
    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke
    endpoint = 'bids/{}'.format(bid_id)
    response = make_put_request(session, endpoint, headers=headers,
                                params_data=bid_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        json_data = response.json()
        raise BidNotRetractedException(message=json_data['message'],
                                       error_code=json_data['error_code'],
                                       request_id=json_data['request_id'])


def highlight_project_bid(session, bid_id):
    """
    Highlight a bid on a project
    """
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    bid_data = {
        'action': 'highlight'
    }
    # POST /api/projects/0.1/bids/{bid_id}/?action=revoke
    endpoint = 'bids/{}'.format(bid_id)
    response = make_put_request(session, endpoint, headers=headers,
                                params_data=bid_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        json_data = response.json()
        raise BidNotHighlightedException(message=json_data['message'],
                                         error_code=json_data['error_code'],
                                         request_id=json_data['request_id'])


def create_milestone_payment(session, project_id, bidder_id, amount,
                             reason, description):
    """
    Create a milestone payment
    """
    milestone_data = {
        'project_id': project_id,
        'bidder_id': bidder_id,
        'amount': amount,
        'reason': reason,
        'description': description
    }
    # POST /api/projects/0.1/milestones/
    response = make_post_request(session, 'milestones',
                                 json_data=milestone_data)
    json_data = response.json()
    if response.status_code == 200:
        milestone_data = json_data['result']
        return Milestone(milestone_data)
    else:
        raise MilestoneNotCreatedException(message=json_data['message'],
                                           error_code=json_data['error_code'],
                                           request_id=json_data['request_id'])

def
create_milestone_payment
(
session
,
project_id
,
bidder_id
,
amount
,
reason
,
description
)
:
milestone_data
=
{
'project_id'
:
project_id
,
'bidder_id'
:
bidder_id
,
'amount'
:
amount
,
'reason'
:
reason
,
'description'
:
description
}
# POST /api/projects/0.1/milestones/
response
=
make_post_request
(
session
,
'milestones'
,
json_data
=
milestone_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
milestone_data
=
json_data
[
'result'
]
return
Milestone
(
milestone_data
)
else
:
raise
MilestoneNotCreatedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def post_track(session, user_id, project_id, latitude, longitude):
    """
    Start tracking a project by creating a track
    """
    tracking_data = {
        'user_id': user_id,
        'project_id': project_id,
        'track_point': {
            'latitude': latitude,
            'longitude': longitude
        }
    }

    # POST /api/projects/0.1/tracks/
    response = make_post_request(session, 'tracks',
                                 json_data=tracking_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise TrackNotCreatedException(message=json_data['message'],
                                       error_code=json_data['error_code'],
                                       request_id=json_data['request_id'])

def
post_track
(
session
,
user_id
,
project_id
,
latitude
,
longitude
)
:
tracking_data
=
{
'user_id'
:
user_id
,
'project_id'
:
project_id
,
'track_point'
:
{
'latitude'
:
latitude
,
'longitude'
:
longitude
}
}
# POST /api/projects/0.1/tracks/
response
=
make_post_request
(
session
,
'tracks'
,
json_data
=
tracking_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
TrackNotCreatedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def update_track(session, track_id, latitude, longitude, stop_tracking=False):
    """
    Updates the current location by creating a new track point and appending
    it to the given track
    """

    tracking_data = {
        'track_point': {
            'latitude': latitude,
            'longitude': longitude,
        },
        'stop_tracking': stop_tracking
    }

    # PUT /api/projects/0.1/tracks/{track_id}/

    response = make_put_request(session, 'tracks/{}'.format(track_id),
                                json_data=tracking_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise TrackNotUpdatedException(message=json_data['message'],
                                       error_code=json_data['error_code'],
                                       request_id=json_data['request_id'])


def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None):
    """
    Gets a specific track
    """

    tracking_data = {}
    if track_point_limit:
        tracking_data['track_point_limit'] = track_point_limit
    if track_point_offset:
        tracking_data['track_point_offset'] = track_point_offset

    # GET /api/projects/0.1/tracks/{track_id}/

    response = make_get_request(session, 'tracks/{}'.format(track_id),
                                params_data=tracking_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise TrackNotFoundException(message=json_data['message'],
                                     error_code=json_data['error_code'],
                                     request_id=json_data['request_id'])


def create_milestone_request(session, project_id, bid_id, description, amount):
    """
    Create a milestone request
    """
    milestone_request_data = {
        'project_id': project_id,
        'bid_id': bid_id,
        'description': description,
        'amount': amount,
    }
    # POST /api/projects/0.1/milestone_requests/
    response = make_post_request(session, 'milestone_requests',
                                 json_data=milestone_request_data)
    json_data = response.json()
    if response.status_code == 200:
        milestone_request_data = json_data['result']
        return MilestoneRequest(milestone_request_data)
    else:
        raise MilestoneRequestNotCreatedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])


def accept_milestone_request(session, milestone_request_id):
    """
    Accept a milestone request
    """
    params_data = {
        'action': 'accept',
    }
    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
    # accept
    endpoint = 'milestone_requests/{}'.format(milestone_request_id)
    response = make_put_request(session, endpoint, params_data=params_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        raise MilestoneRequestNotAcceptedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])


def reject_milestone_request(session, milestone_request_id):
    """
    Reject a milestone request
    """
    params_data = {
        'action': 'reject',
    }
    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
    # reject
    endpoint = 'milestone_requests/{}'.format(milestone_request_id)
    response = make_put_request(session, endpoint, params_data=params_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        raise MilestoneRequestNotRejectedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])


def delete_milestone_request(session, milestone_request_id):
    """
    Delete a milestone request
    """
    params_data = {
        'action': 'delete',
    }
    # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
    # delete
    endpoint = 'milestone_requests/{}'.format(milestone_request_id)
    response = make_put_request(session, endpoint, params_data=params_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        raise MilestoneRequestNotDeletedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])


def post_review(session, review):
    """
    Post a review
    """
    # POST /api/projects/0.1/reviews/
    response = make_post_request(session, 'reviews', json_data=review)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['status']
    else:
        raise ReviewNotPostedException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])

def
post_review
(
session
,
review
)
:
# POST /api/projects/0.1/reviews/
response
=
make_post_request
(
session
,
'reviews'
,
json_data
=
review
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'status'
]
else
:
raise
ReviewNotPostedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def get_jobs(session, job_ids, seo_details, lang):
    """
    Get a list of jobs
    """
    get_jobs_data = {
        'jobs[]': job_ids,
        'seo_details': seo_details,
        'lang': lang,
    }
    # GET /api/projects/0.1/jobs/
    response = make_get_request(session, 'jobs', params_data=get_jobs_data)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise JobsNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id'])

def
get_jobs
(
session
,
job_ids
,
seo_details
,
lang
)
:
get_jobs_data
=
{
'jobs[]'
:
job_ids
,
'seo_details'
:
seo_details
,
'lang'
:
lang
,
}
# GET /api/projects/0.1/jobs/
response
=
make_get_request
(
session
,
'jobs'
,
params_data
=
get_jobs_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
JobsNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def create_thread(session, member_ids, context_type, context, message):
    """
    Create a thread
    """
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    thread_data = {
        'members[]': member_ids,
        'context_type': context_type,
        'context': context,
        'message': message,
    }

    # POST /api/messages/0.1/threads/
    response = make_post_request(session, 'threads', headers,
                                 form_data=thread_data)
    json_data = response.json()
    if response.status_code == 200:
        return Thread(json_data['result'])
    else:
        raise ThreadNotCreatedException(message=json_data['message'],
                                        error_code=json_data['error_code'],
                                        request_id=json_data['request_id'])

def
create_thread
(
session
,
member_ids
,
context_type
,
context
,
message
)
:
headers
=
{
'Content-Type'
:
'application/x-www-form-urlencoded'
}
thread_data
=
{
'members[]'
:
member_ids
,
'context_type'
:
context_type
,
'context'
:
context
,
'message'
:
message
,
}
# POST /api/messages/0.1/threads/
response
=
make_post_request
(
session
,
'threads'
,
headers
,
form_data
=
thread_data
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
Thread
(
json_data
[
'result'
]
)
else
:
raise
ThreadNotCreatedException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def create_project_thread(session, member_ids, project_id, message):
    """
    Create a project thread
    """
    return create_thread(session, member_ids, 'project', project_id, message)

def create_project_thread ( session , member_ids , project_id , message ) : return create_thread ( session , member_ids , 'project' , project_id , message )


def get_messages(session, query, limit=10, offset=0):
    """
    Get one or more messages
    """
    query['limit'] = limit
    query['offset'] = offset

    # GET /api/messages/0.1/messages
    response = make_get_request(session, 'messages', params_data=query)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise MessagesNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )

def
get_messages
(
session
,
query
,
limit
=
10
,
offset
=
0
)
:
query
[
'limit'
]
=
limit
query
[
'offset'
]
=
offset
# GET /api/messages/0.1/messages
response
=
make_get_request
(
session
,
'messages'
,
params_data
=
query
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
MessagesNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def search_messages(session, thread_id, query, limit=20,
                    offset=0, message_context_details=None,
                    window_above=None, window_below=None):
    """
    Search for messages
    """
    query = {
        'thread_id': thread_id,
        'query': query,
        'limit': limit,
        'offset': offset
    }
    if message_context_details:
        query['message_context_details'] = message_context_details
    if window_above:
        query['window_above'] = window_above
    if window_below:
        query['window_below'] = window_below

    # GET /api/messages/0.1/messages/search
    response = make_get_request(session, 'messages/search', params_data=query)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise MessagesNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )

def
search_messages
(
session
,
thread_id
,
query
,
limit
=
20
,
offset
=
0
,
message_context_details
=
,
window_above
=
,
window_below
=
)
:
query
=
{
'thread_id'
:
thread_id
,
'query'
:
query
,
'limit'
:
limit
,
'offset'
:
offset
}
if
message_context_details
:
query
[
'message_context_details'
]
=
message_context_details
if
window_above
:
query
[
'window_above'
]
=
window_above
if
window_below
:
query
[
'window_below'
]
=
window_below
# GET /api/messages/0.1/messages/search
response
=
make_get_request
(
session
,
'messages/search'
,
params_data
=
query
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
MessagesNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def get_threads(session, query):
    """
    Get one or more threads
    """
    # GET /api/messages/0.1/threads
    response = make_get_request(session, 'threads', params_data=query)
    json_data = response.json()
    if response.status_code == 200:
        return json_data['result']
    else:
        raise ThreadsNotFoundException(
            message=json_data['message'],
            error_code=json_data['error_code'],
            request_id=json_data['request_id']
        )

def
get_threads
(
session
,
query
)
:
# GET /api/messages/0.1/threads
response
=
make_get_request
(
session
,
'threads'
,
params_data
=
query
)
json_data
=
response
.
json
(
)
if
response
.
status_code
==
200
:
return
json_data
[
'result'
]
else
:
raise
ThreadsNotFoundException
(
message
=
json_data
[
'message'
]
,
error_code
=
json_data
[
'error_code'
]
,
request_id
=
json_data
[
'request_id'
]
)


def _clean(zipcode, valid_length=_valid_zipcode_length):
    """ Assumes zipcode is of type `str` """
    zipcode = zipcode.split("-")[0]  # Convert #####-#### to #####

    if len(zipcode) != valid_length:
        raise ValueError(
            'Invalid format, zipcode must be of the format: "#####" or "#####-####"'
        )

    if _contains_nondigits(zipcode):
        raise ValueError('Invalid characters, zipcode may only contain digits and "-".')

    return zipcode


def similar_to(partial_zipcode, zips=_zips):
    """ List of zipcode dicts where zipcode prefix matches `partial_zipcode` """
    return [z for z in zips if z["zip_code"].startswith(partial_zipcode)]

def similar_to ( partial_zipcode , zips = _zips ) : return [ z for z in zips if z [ "zip_code" ] . startswith ( partial_zipcode ) ]

List of zipcode dicts where zipcode prefix matches partial_zipcode


def filter_by(zips=_zips, **kwargs):
    """ Use `kwargs` to select for desired attributes from list of zipcode dicts """
    return [z for z in zips if all([k in z and z[k] == v for k, v in kwargs.items()])]

def filter_by ( zips = _zips , * * kwargs ) : return [ z for z in zips if all ( [ k in z and z [ k ] == v for k , v in kwargs . items ( ) ] ) ]

Use kwargs to select for desired attributes from list of zipcode dicts


def is_valid_identifier(name):
    """Pedantic yet imperfect. Test to see if "name" is a valid python identifier
    """
    if not isinstance(name, str):
        return False
    if '\n' in name:
        return False
    if name.strip() != name:
        return False
    try:
        code = compile('\n{0}=None'.format(name), filename='<string>', mode='single')
        exec(code)
        return True
    except SyntaxError:
        return False

def is_valid_identifier ( name ) : if not isinstance ( name , str ) : return False if '\n' in name : return False if name . strip ( ) != name : return False try : code = compile ( '\n{0}=None' . format ( name ) , filename = '<string>' , mode = 'single' ) exec ( code ) return True except SyntaxError : return False

Pedantic yet imperfect . Test to see if name is a valid python identifier


def from_config(
            cls, cfg,
            default_fg=DEFAULT_FG_16, default_bg=DEFAULT_BG_16,
            default_fg_hi=DEFAULT_FG_256, default_bg_hi=DEFAULT_BG_256,
            max_colors=2**24
    ):
        """
        Build a palette definition from either a simple string or a dictionary,
        filling in defaults for items not specified.

        e.g.:
            "dark green"
                dark green foreground, black background

            {lo: dark gray, hi: "#666"}
                dark gray on 16-color terminals, #666 for 256+ color

        """
        # TODO: mono

        e = PaletteEntry(mono = default_fg,
                         foreground=default_fg,
                         background=default_bg,
                         foreground_high=default_fg_hi,
                         background_high=default_bg_hi)

        if isinstance(cfg, str):
            e.foreground_high = cfg
            if e.allowed(cfg, 16):
                e.foreground = cfg
            else:
                rgb = AttrSpec(fg=cfg, bg="", colors=max_colors).get_rgb_values()[0:3]
                e.foreground = nearest_basic_color(rgb)

        elif isinstance(cfg, dict):

            bg = cfg.get("bg", None)
            if isinstance(bg, str):
                e.background_high = bg
                if e.allowed(bg, 16):
                    e.background = bg
                else:
                    rgb = AttrSpec(fg=bg, bg="", colors=max_colors).get_rgb_values()[0:3]
                    e.background = nearest_basic_color(rgb)
            elif isinstance(bg, dict):
                e.background_high = bg.get("hi", default_bg_hi)
                if "lo" in bg:
                    if e.allowed(bg["lo"], 16):
                        e.background = bg["lo"]
                    else:
                        rgb = AttrSpec(fg=bg["lo"], bg="", colors=max_colors).get_rgb_values()[0:3]
                        e.background = nearest_basic_color(rgb)

            fg = cfg.get("fg", cfg)
            if isinstance(fg, str):
                e.foreground_high = fg
                if e.allowed(fg, 16):
                    e.foreground = fg
                else:
                    rgb = AttrSpec(fg=fg, bg="", colors=max_colors).get_rgb_values()[0:3]
                    e.foreground = nearest_basic_color(rgb)

            elif isinstance(fg, dict):
                e.foreground_high = fg.get("hi", default_fg_hi)
                if "lo" in fg:
                    if e.allowed(fg["lo"], 16):
                        e.foreground = fg["lo"]
                    else:
                        rgb = AttrSpec(fg=fg["lo"], bg="", colors=max_colors).get_rgb_values()[0:3]
                        e.foreground = nearest_basic_color(rgb)
        return e

def
from_config
(
cls
,
cfg
,
default_fg
=
DEFAULT_FG_16
,
default_bg
=
DEFAULT_BG_16
,
default_fg_hi
=
DEFAULT_FG_256
,
default_bg_hi
=
DEFAULT_BG_256
,
max_colors
=
2
**
24
)
:
# TODO: mono
e
=
PaletteEntry
(
mono
=
default_fg
,
foreground
=
default_fg
,
background
=
default_bg
,
foreground_high
=
default_fg_hi
,
background_high
=
default_bg_hi
)
if
isinstance
(
cfg
,
str
)
:
e
.
foreground_high
=
cfg
if
e
.
allowed
(
cfg
,
16
)
:
e
.
foreground
=
cfg
else
:
rgb
=
AttrSpec
(
fg
=
cfg
,
bg
=
""
,
colors
=
max_colors
)
.
get_rgb_values
(
)
[
0
:
3
]
e
.
foreground
=
nearest_basic_color
(
rgb
)
elif
isinstance
(
cfg
,
dict
)
:
bg
=
cfg
.
get
(
"bg"
,
)
if
isinstance
(
bg
,
str
)
:
e
.
background_high
=
bg
if
e
.
allowed
(
bg
,
16
)
:
e
.
background
=
bg
else
:
rgb
=
AttrSpec
(
fg
=
bg
,
bg
=
""
,
colors
=
max_colors
)
.
get_rgb_values
(
)
[
0
:
3
]
e
.
background
=
nearest_basic_color
(
rgb
)
elif
isinstance
(
bg
,
dict
)
:
e
.
background_high
=
bg
.
get
(
"hi"
,
default_bg_hi
)
if
"lo"
in
bg
:
if
e
.
allowed
(
bg
[
"lo"
]
,
16
)
:
e
.
background
=
bg
[
"lo"
]
else
:
rgb
=
AttrSpec
(
fg
=
bg
[
"lo"
]
,
bg
=
""
,
colors
=
max_colors
)
.
get_rgb_values
(
)
[
0
:
3
]
e
.
background
=
nearest_basic_color
(
rgb
)
fg
=
cfg
.
get
(
"fg"
,
cfg
)
if
isinstance
(
fg
,
str
)
:
e
.
foreground_high
=
fg
if
e
.
allowed
(
fg
,
16
)
:
e
.
foreground
=
fg
else
:
rgb
=
AttrSpec
(
fg
=
fg
,
bg
=
""
,
colors
=
max_colors
)
.
get_rgb_values
(
)
[
0
:
3
]
e
.
foreground
=
nearest_basic_color
(
rgb
)
elif
isinstance
(
fg
,
dict
)
:
e
.
foreground_high
=
fg
.
get
(
"hi"
,
default_fg_hi
)
if
"lo"
in
fg
:
if
e
.
allowed
(
fg
[
"lo"
]
,
16
)
:
e
.
foreground
=
fg
[
"lo"
]
else
:
rgb
=
AttrSpec
(
fg
=
fg
[
"lo"
]
,
bg
=
""
,
colors
=
max_colors
)
.
get_rgb_values
(
)
[
0
:
3
]
e
.
foreground
=
nearest_basic_color
(
rgb
)
return
e

Build a palette definition from either a simple string or a dictionary filling in defaults for items not specified .


def migrate(src_path,
            src_passphrase,
            src_backend,
            dst_path,
            dst_passphrase,
            dst_backend):
    """Migrate all keys in a source stash to a destination stash

    The migration process will decrypt all keys using the source
    stash's passphrase and then encrypt them based on the destination
    stash's passphrase.

    re-encryption will take place only if the passphrases are differing
    """
    src_storage = STORAGE_MAPPING[src_backend](**_parse_path_string(src_path))
    dst_storage = STORAGE_MAPPING[dst_backend](**_parse_path_string(dst_path))
    src_stash = Stash(src_storage, src_passphrase)
    dst_stash = Stash(dst_storage, dst_passphrase)
    # TODO: Test that re-encryption does not occur on similar
    # passphrases
    keys = src_stash.export()
    dst_stash.load(src_passphrase, keys=keys)


def generate_passphrase(size=12):
    """Return a generate string `size` long based on lowercase, uppercase,
    and digit chars
    """
    chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
    return str(''.join(random.choice(chars) for _ in range(size)))

def generate_passphrase ( size = 12 ) : chars = string . ascii_lowercase + string . ascii_uppercase + string . digits return str ( '' . join ( random . choice ( chars ) for _ in range ( size ) ) )

Return a generate string size long based on lowercase uppercase and digit chars