requests.codes.accepted

Here are the examples of the python api requests.codes.accepted taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

23 Examples 7

Example 1

Project: rides-python-sdk Source File: test_client.py
@uber_vcr.use_cassette()
def test_request_ride(authorized_sandbox_client):
    """Test to request ride with access token."""
    response = authorized_sandbox_client.request_ride(
        product_id=PRODUCT_ID,
        start_latitude=START_LAT,
        start_longitude=START_LNG,
        end_latitude=END_LAT,
        end_longitude=END_LNG,
    )
    assert response.status_code == codes.accepted

    # assert response looks like ride details
    response = response.json
    assert EXPECTED_RIDE_DETAILS_KEYS.issubset(response)

Example 2

Project: rides-python-sdk Source File: test_client.py
@uber_vcr.use_cassette()
def test_request_shared_ride(authorized_sandbox_client):
    """Test to request shared ride with access token."""
    try:
        response = authorized_sandbox_client.request_ride(
            product_id=SHARED_PRODUCT_ID,
            fare_id=SHARED_FARE_ID,
            seat_count=SHARED_SEAT_COUNT,
            start_latitude=START_LAT,
            start_longitude=START_LNG,
            end_latitude=END_LAT,
            end_longitude=END_LNG,
        )
    except Exception as e:
        print(e)
        print(e.errors[0].__dict__)
    assert response.status_code == codes.accepted

Example 3

Project: rides-python-sdk Source File: test_client.py
@uber_vcr.use_cassette()
def test_request_ride_without_destination(authorized_sandbox_client):
    """Test to request ride without a destination."""
    response = authorized_sandbox_client.request_ride(
        product_id=PRODUCT_ID,
        start_latitude=START_LAT,
        start_longitude=START_LNG,
    )
    assert response.status_code == codes.accepted

    # assert response looks like ride details
    response = response.json
    assert EXPECTED_RIDE_DETAILS_KEYS.issubset(response)

Example 4

Project: rides-python-sdk Source File: test_client.py
@uber_vcr.use_cassette()
def test_request_ride_with_no_default_product(authorized_sandbox_client):
    """Test to request ride with no default product."""
    response = authorized_sandbox_client.request_ride(
        start_latitude=START_LAT,
        start_longitude=START_LNG,
        end_latitude=END_LAT,
        end_longitude=END_LNG,
    )
    assert response.status_code == codes.accepted

    # assert response looks like ride details
    response = response.json
    assert EXPECTED_RIDE_DETAILS_KEYS.issubset(response)

Example 5

Project: rides-python-sdk Source File: test_client.py
@uber_vcr.use_cassette()
def test_request_ride_with_places(authorized_sandbox_client):
    """Test to request ride with place ids."""
    response = authorized_sandbox_client.request_ride(
        product_id=PRODUCT_ID,
        start_place_id='home',
        end_place_id='work',
    )
    assert response.status_code == codes.accepted

    # assert response looks like ride details
    response = response.json
    assert EXPECTED_RIDE_DETAILS_KEYS.issubset(response)

Example 6

Project: pyvcloud Source File: gateway.py
    def save_services_configuration(self):
        edgeGatewayServiceConfiguration = self.me.get_Configuration().get_EdgeGatewayServiceConfiguration()
        body = '<?xml version="1.0" encoding="UTF-8"?>' + \
               CommonUtils.convertPythonObjToStr(self.me.get_Configuration().get_EdgeGatewayServiceConfiguration(),
                                                 name='EdgeGatewayServiceConfiguration',
                                                 namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ')
        content_type = "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml"
        link = filter(lambda link: link.get_type() == content_type, self.me.get_Link())
        self.response = Http.post(link[0].get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
        if self.response.status_code == requests.codes.accepted:
            task = taskType.parseString(self.response.content, True)
            return task

Example 7

Project: pysensu Source File: pysensu.py
Function: request_check
    def request_check(self, check, subscribers):
        data = {
            "check": check,
            "subscribers": subscribers
        }
        r = self._api_call("{}/check/request".format(self.api_url), "post", json.dumps(data))
        if r.status_code != requests.codes.accepted:
            raise ValueError("Error requesting check ({}, {})".format(r.status_code, r.json))

Example 8

Project: pysensu Source File: pysensu.py
Function: resolve_event
    def resolve_event(self, client, check):
        data = {
            "client": client,
            "check": check
        }
        r = self._api_call("{}/event/resolve".format(self.api_url), "post", json.dumps(data))
        if r.status_code != requests.codes.accepted:
            raise ValueError("Error getting client({})".format(r.status_code))

Example 9

Project: pyvcloud Source File: gateway.py
    def set_syslog_conf(self, syslog_server_ip):
        headers = self.headers
        headers['Accept'] = 'application/*+xml;version=5.11'
        headers['Content-Type'] = 'application/vnd.vmware.vcloud.SyslogSettings+xml;version=5.11'
        # content_type = "application/vnd.vmware.vcloud.SyslogSettings+xml"
        body = ''
        if '' == syslog_server_ip:
            body = """
            <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd">
                  <TenantSyslogServerSettings>
                  </TenantSyslogServerSettings>
              </SyslogServerSettings>
                    """
        else:
            body = """
            <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd">
                <TenantSyslogServerSettings>
                    <SyslogServerIp>%s</SyslogServerIp>
                </TenantSyslogServerSettings>
            </SyslogServerSettings>
            """ % syslog_server_ip
        # '<SyslogServerSettings><TenantSyslogServerSettings><SyslogServerIp>%s</SyslogServerIp></TenantSyslogServerSettings></SyslogServerSettings>' % syslog_server_ip
        # link = filter(lambda link: link.get_type() == content_type, self.me.get_Link())
        self.response = Http.post(self.me.href+'/action/configureSyslogServerSettings', data=body, headers=headers, verify=self.verify, logger=self.logger)
        if self.response.status_code == requests.codes.accepted:
            task = taskType.parseString(self.response.content, True)
            return task

Example 10

Project: pyvcloud Source File: vapp.py
    def execute(self, operation, http, body=None, targetVM=None):
        """
        Execute an operation against a VM as an Asychronous Task.

        :param operation: (str): The command to execute
        :param http: (str): The http operation.
        :param body: (str, optional): a body for the http request
        :param targetVM: (str, optional): The name of the VM that will be the target of the request.
        :return: (TaskType or Bool) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                Or False if the request failed, error and debug level messages are logged.

        """
        vApp = targetVM if targetVM else self.me
        link = filter(lambda link: link.get_rel() == operation, vApp.get_Link())
        if not link:
            Log.error(self.logger, "link not found; rel=%s" % operation)
            Log.debug(self.logger, "vApp href=%s, name=%s" % (vApp.get_href(), vApp.get_name()))
            return False
        else:
            if http == "post":
                headers = self.headers
                if body and body.startswith('<DeployVAppParams '):
                    headers['Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml'
                elif body and body.startswith('<UndeployVAppParams '):
                    headers['Content-type'] = 'application/vnd.vmware.vcloud.undeployVAppParams+xml'
                elif body and body.startswith('<CreateSnapshotParams '):
                    headers['Content-type'] = 'application/vnd.vmware.vcloud.createSnapshotParams+xml'
                self.response = Http.post(link[0].get_href(), data=body, headers=headers, verify=self.verify, logger=self.logger)
            elif http == "put":
                self.response = Http.put(link[0].get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
            else:
                self.response = Http.delete(link[0].get_href(), headers=self.headers, verify=self.verify, logger=self.logger)
            if self.response.status_code == requests.codes.accepted:
                return taskType.parseString(self.response.content, True)
            else:
                Log.debug(self.logger, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text))
                return False

Example 11

Project: pyvcloud Source File: vapp.py
    def connect_vms(self, network_name, connection_index,
                    connections_primary_index=None, ip_allocation_mode='DHCP',
                    mac_address=None, ip_address=None):
        """
        Attach vms to a virtual network.

        something helpful.

        :param network_name: (str): The network name to connect the VM to.
        :param connection_index: (str): Virtual slot number associated with this NIC. First slot number is 0.
        :param connections_primary_index: (str): Virtual slot number associated with the NIC that should be considered this \n
                  virtual machine's primary network connection. Defaults to slot 0.
        :param ip_allocation_mode: (str, optional): IP address allocation mode for this connection.

                                 * One of:

                                  - POOL (A static IP address is allocated automatically from a pool of addresses.)

                                  - DHCP (The IP address is obtained from a DHCP service.)

                                  - MANUAL (The IP address is assigned manually in the IpAddress element.)

                                  - NONE (No IP addressing mode specified.)

        :param mac_address: (str):    the MAC address associated with the NIC.
        :param ip_address: (str):     the IP address assigned to this NIC.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.


        """
        children = self.me.get_Children()
        if children:
            vms = children.get_Vm()
            for vm in vms:
                new_connection = self._create_networkConnection(
                    network_name, connection_index, ip_allocation_mode,
                    mac_address, ip_address)
                networkConnectionSection = [section for section in vm.get_Section() if isinstance(section, NetworkConnectionSectionType)][0]
                self._modify_networkConnectionSection(
                    networkConnectionSection,
                    new_connection,
                    connections_primary_index)
                output = StringIO()
                networkConnectionSection.export(output,
                    0,
                    name_ = 'NetworkConnectionSection',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                    pretty_print = True)
                body=output.getvalue().replace("vmw:Info", "ovf:Info")
                self.response = Http.put(vm.get_href() + "/networkConnectionSection/", data=body, headers=self.headers, verify=self.verify, logger=self.logger)
                if self.response.status_code == requests.codes.accepted:
                    return taskType.parseString(self.response.content, True)

Example 12

Project: pyvcloud Source File: vapp.py
    def disconnect_vms(self, network_name=None):
        """
        Disconnect the vm from the vapp network.

        :param network_name: (string): The name of the vApp network. If None, then disconnect from all the networks.
        :return: (bool): True if the user was vApp was successfully deployed, False otherwise.

        """
        children = self.me.get_Children()
        if children:
            vms = children.get_Vm()
            for vm in vms:
                Log.debug(self.logger, "child VM name=%s" % vm.get_name())
                networkConnectionSection = [section for section in vm.get_Section() if isinstance(section, NetworkConnectionSectionType)][0]
                found = -1
                if network_name is None:
                    networkConnectionSection.set_NetworkConnection([])
                    found = 1
                else:
                    for index, networkConnection in enumerate(networkConnectionSection.get_NetworkConnection()):
                        if networkConnection.get_network() == network_name:
                            found = index
                            break
                    if found != -1:
                        networkConnectionSection.NetworkConnection.pop(found)
                if found != -1:
                    output = StringIO()
                    networkConnectionSection.export(output,
                        0,
                        name_ = 'NetworkConnectionSection',
                        namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                        pretty_print = True)
                    body=output.getvalue().replace("vmw:Info", "ovf:Info")
                    self.response = Http.put(vm.get_href() + "/networkConnectionSection/", data=body, headers=self.headers, verify=self.verify, logger=self.logger)
                    if self.response.status_code == requests.codes.accepted:
                        return taskType.parseString(self.response.content, True)
        task = TaskType()
        task.set_status("success")
        task.set_Progress("100")
        return task

Example 13

Project: pyvcloud Source File: vapp.py
    def connect_to_network(self, network_name, network_href, fence_mode='bridged'):
        """
        Connect the vApp to an existing virtual network in the VDC.

        :param network_name: (str): The name of the virtual network.
        :param network_href: (str): A uri that points to the network resource.
        :param fence_mode: (str, optional):
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.

        """
        vApp_NetworkConfigSection = [section for section in self.me.get_Section() if section.__class__.__name__ == "NetworkConfigSectionType"][0]
        link = [link for link in vApp_NetworkConfigSection.get_Link() if link.get_type() == "application/vnd.vmware.vcloud.networkConfigSection+xml"][0]
        for networkConfig in vApp_NetworkConfigSection.get_NetworkConfig():
            if networkConfig.get_networkName() == network_name:
                task = TaskType()
                task.set_status("success")
                task.set_Progress("100")
                return task
        networkConfigSection = VAPP.create_networkConfigSection(network_name, network_href, fence_mode, vApp_NetworkConfigSection)
        output = StringIO()
        networkConfigSection.export(output,
            0,
            name_ = 'NetworkConfigSection',
            namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
            pretty_print = True)
        body = output.getvalue().\
            replace('Info msgid=""', "ovf:Info").replace("Info", "ovf:Info").replace(":vmw", "").replace("vmw:","")\
            .replace("RetainNetovf", "ovf").replace("ovf:InfoAcrossDeployments","RetainNetInfoAcrossDeployments")
        self.response = Http.put(link.get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
        if self.response.status_code == requests.codes.accepted:
            return taskType.parseString(self.response.content, True)

Example 14

Project: pyvcloud Source File: vapp.py
    def disconnect_from_networks(self):
        """
        Disconnect the vApp from currently connected virtual networks.

        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.

        """
        networkConfigSection = [section for section in self.me.get_Section() if section.__class__.__name__ == "NetworkConfigSectionType"][0]
        link = [link for link in networkConfigSection.get_Link() if link.get_type() == "application/vnd.vmware.vcloud.networkConfigSection+xml"][0]
        networkConfigSection.NetworkConfig[:] = []
        output = StringIO()
        networkConfigSection.export(output,
            0,
            name_ = 'NetworkConfigSection',
            namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
            pretty_print = True)
        body = output.getvalue().\
                replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                replace("/Info", "/ovf:Info")
        self.response = Http.put(link.get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
        if self.response.status_code == requests.codes.accepted:
            return taskType.parseString(self.response.content, True)

Example 15

Project: pyvcloud Source File: vapp.py
    def disconnect_from_network(self, network_name):
        """
        Disconnect the vApp from an existing virtual network in the VDC.

        :param network_name: (str): The name of the virtual network.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.

        """

        networkConfigSection = [section for section in self.me.get_Section() if section.__class__.__name__ == "NetworkConfigSectionType"][0]
        link = [link for link in networkConfigSection.get_Link() if link.get_type() == "application/vnd.vmware.vcloud.networkConfigSection+xml"][0]
        found = -1
        for index, networkConfig in enumerate(networkConfigSection.get_NetworkConfig()):
            if networkConfig.get_networkName() == network_name:
                found = index
        if found != -1:
            networkConfigSection.NetworkConfig.pop(found)
            output = StringIO()
            networkConfigSection.export(output,
                0,
                name_ = 'NetworkConfigSection',
                namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                pretty_print = True)
            body = output.getvalue().\
                    replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                    replace("/Info", "/ovf:Info")
            self.response = Http.put(link.get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
            if self.response.status_code == requests.codes.accepted:
                return taskType.parseString(self.response.content, True)

Example 16

Project: pyvcloud Source File: vapp.py
    def customize_guest_os(self, vm_name, customization_script=None,
                           computer_name=None, admin_password=None,
                           reset_password_required=False):
        """
        Associate a customization script with a guest OS and execute the script.
        The VMware tools must be installed in the Guest OS.

        :param vm_name: (str): The name of the vm to be customized.
        :param customization_script: (str, Optional): The path to a file on the local file system containing the customization script.
        :param computer_name: (str, Optional): A new value for the the computer name. A default value for the template is used if a value is not set.
        :param admin_password: (str, Optional): A password value for the admin/root user. A password is autogenerated if a value is not supplied.
        :param reset_password_required: (bool): Force the user to reset the password on first login.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        """
        children = self.me.get_Children()
        if children:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vms[0].get_Section()
                customization_section = [section for section in sections
                         if (section.__class__.__name__ ==
                             "GuestCustomizationSectionType")
                         ][0]
                customization_section.set_Enabled(True)
                customization_section.set_ResetPasswordRequired(
                    reset_password_required)
                customization_section.set_AdminAutoLogonEnabled(False)
                customization_section.set_AdminAutoLogonCount(0)
                if customization_script:
                    customization_section.set_CustomizationScript(
                        customization_script)
                if computer_name:
                    customization_section.set_ComputerName(computer_name)
                if admin_password:
                    customization_section.set_AdminPasswordEnabled(True)
                    customization_section.set_AdminPasswordAuto(False)
                    customization_section.set_AdminPassword(admin_password)
                output = StringIO()
                customization_section.export(output,
                    0,
                    name_ = 'GuestCustomizationSection',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                    pretty_print = True)
                body = output.getvalue().\
                    replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                    replace("/Info", "/ovf:Info")
                headers = self.headers
                headers['Content-type'] = 'application/vnd.vmware.vcloud.guestcustomizationsection+xml'
                self.response = Http.put(customization_section.Link[0].href, data=body, headers=headers, verify=self.verify, logger=self.logger)
                if self.response.status_code == requests.codes.accepted:
                    return taskType.parseString(self.response.content, True)
                else:
                    Log.debug(self.logger, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text))

Example 17

Project: pyvcloud Source File: vapp.py
    def force_customization(self, vm_name, power_on=True):
        """
        Force the guest OS customization script to be run for a specific vm in the vApp.
        A customization script must have been previously associated with the VM
        using the pyvcloud customize_guest_os method or using the vCD console
        The VMware tools must be installed in the Guest OS.

        :param vm_name: (str): The name of the vm to be customized.
        :param power_on (bool): Wether to power the vm on after customization or not
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.b\n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        """
        children = self.me.get_Children()
        if children:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vms[0].get_Section()
                links = filter(lambda link: link.rel== "deploy", vms[0].Link)
                if len(links) == 1:
                    forceCustomizationValue = 'true'
                    deployVAppParams = vcloudType.DeployVAppParamsType()
                    if power_on:
                        deployVAppParams.set_powerOn('true')
                    else:
                        deployVAppParams.set_powerOn('false')
                    deployVAppParams.set_deploymentLeaseSeconds(0)
                    deployVAppParams.set_forceCustomization('true')
                    body = CommonUtils.convertPythonObjToStr(deployVAppParams, name = "DeployVAppParams",
                            namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"')
                    headers = self.headers
                    headers['Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml'
                    self.response = Http.post(links[0].href, data=body, headers=headers, verify=self.verify, logger=self.logger)
                    if self.response.status_code == requests.codes.accepted:
                        return taskType.parseString(self.response.content, True)
                    else:
                        Log.debug(self.logger, "response status=%d, content=%s" % (self.response.status_code, self.response.text))

Example 18

Project: pyvcloud Source File: vapp.py
    def modify_vm_name(self, vm_index, vm_name):
        """
        Modify the name of a VM in a vApp

        :param vm_index: (int):The index of the VM in the vApp 1==first VM
        :param vm_name: (str): The new name of the VM.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        :raises: Exception: If the named VM cannot be located or another error occured.
        """
        children = self.me.get_Children()
        if children:
            assert len(children.get_Vm()) >= vm_index
            vm = children.get_Vm()[vm_index-1]
            assert vm
            href = vm.get_href()
            vm_name_old = vm.get_name()
            Log.debug(self.logger, "VM name change (%s) %s -> %s" % (vm_index, vm_name_old, vm_name))
            vm.set_name(vm_name)
            vm.set_Section([])
            output = StringIO()
            vm.export(output,
                0,
                name_ = 'Vm',
                namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                pretty_print = True)
            body = output.getvalue()
            headers = self.headers
            headers['Content-type'] = 'application/vnd.vmware.vcloud.vm+xml'
            self.response = Http.post(href+'/action/reconfigureVm', data=body, headers=headers, verify=self.verify, logger=self.logger)
            if self.response.status_code == requests.codes.accepted:
                return taskType.parseString(self.response.content, True)
            else:
                raise Exception(self.response.status_code)
        raise Exception('can\'t find vm')

Example 19

Project: pyvcloud Source File: vapp.py
    def modify_vm_memory(self, vm_name, new_size):
        """
        Modify the virtual Memory allocation for VM.

        :param vm_name: (str): The name of the vm to be customized.
        :param new_size: (int): The new memory allocation in MB.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        :raises: Exception: If the named VM cannot be located or another error occured.
        """
        children = self.me.get_Children()
        if children:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vm.get_Section()
                virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0]
                items = virtualHardwareSection.get_Item()
                memory = filter(lambda item: item.get_Description().get_valueOf_() == "Memory Size", items)[0]
                href = memory.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href')
                en = memory.get_ElementName()
                en.set_valueOf_('%s MB of memory' % new_size)
                memory.set_ElementName(en)
                vq = memory.get_VirtualQuantity()
                vq.set_valueOf_(new_size)
                memory.set_VirtualQuantity(vq)
                weight = memory.get_Weight()
                weight.set_valueOf_(str(int(new_size)*10))
                memory.set_Weight(weight)
                memory_string = CommonUtils.convertPythonObjToStr(memory, 'Memory')
                Log.debug(self.logger, "memory: \n%s" % memory_string)
                output = StringIO()
                memory.export(output,
                    0,
                    name_ = 'Item',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"',
                    pretty_print = True)
                body = output.getvalue().\
                    replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\
                    replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType")
                headers = self.headers
                headers['Content-type'] = 'application/vnd.vmware.vcloud.rasdItem+xml'
                self.response = Http.put(href, data=body, headers=headers, verify=self.verify, logger=self.logger)
                if self.response.status_code == requests.codes.accepted:
                    return taskType.parseString(self.response.content, True)
                else:
                    raise Exception(self.response.status_code)
        raise Exception('can\'t find vm')

Example 20

Project: pyvcloud Source File: vapp.py
    def modify_vm_cpu(self, vm_name, cpus):
        """
        Modify the virtual CPU allocation for VM.

        :param vm_name: (str): The name of the vm to be customized.
        :param cpus: (int): The number of virtual CPUs allocated to the VM.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        :raises: Exception: If the named VM cannot be located or another error occured.
        """
        children = self.me.get_Children()
        if children:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vm.get_Section()
                virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0]
                items = virtualHardwareSection.get_Item()
                cpu = filter(lambda item: (item.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href') != None and item.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href').endswith('/virtualHardwareSection/cpu')), items)[0]
                href = cpu.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href')
                en = cpu.get_ElementName()
                en.set_valueOf_('%s virtual CPU(s)' % cpus)
                cpu.set_ElementName(en)
                vq = cpu.get_VirtualQuantity()
                vq.set_valueOf_(cpus)
                cpu.set_VirtualQuantity(vq)
                cpu_string = CommonUtils.convertPythonObjToStr(cpu, 'CPU')
                output = StringIO()
                cpu.export(output,
                    0,
                    name_ = 'Item',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"',
                    pretty_print = True)
                body = output.getvalue().\
                    replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\
                    replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType")
                headers = self.headers
                headers['Content-type'] = 'application/vnd.vmware.vcloud.rasdItem+xml'
                self.response = Http.put(href, data=body, headers=headers, verify=self.verify, logger=self.logger)
                if self.response.status_code == requests.codes.accepted:
                    return taskType.parseString(self.response.content, True)
                else:
                    raise Exception(self.response.status_code)
        raise Exception('can\'t find vm')

Example 21

Project: eulfedora Source File: api.py
    def upload(self, data, callback=None, content_type=None,
               size=None):
        '''
        Upload a multi-part file for content to ingest.  Returns a
        temporary upload id that can be used as a datstream location.

        :param data: content string, file-like object, or iterable with
            content to be uploaded
        :param callback: optional callback method to monitor the upload;
            see :mod:`requests-toolbelt` docuementation for more
            details: https://toolbelt.readthedocs.org/en/latest/user.html#uploading-data
        :param content_type: optional content type of the data
        :param size: optional size of the data; required when using an
            iterable for the data

        :returns: upload id on success
        '''
        url = 'upload'
        # fedora only expects content uploaded as multipart file;
        # make string content into a file-like object so requests.post
        # sends it the way Fedora expects.
        # NOTE: checking for both python 2.x next method and
        # python 3.x __next__ to test if data is iteraable
        if not hasattr(data, 'read') and \
          not (hasattr(data, '__next__') or hasattr(data, 'next')):
            data = six.BytesIO(force_bytes(data))

        # if data is an iterable, wrap in a readable iterator that
        # requests-toolbelt can read data from
        elif not hasattr(data, 'read') and \
          (hasattr(data, '__next__') or hasattr(data, 'next')):
            if size is None:
                raise Exception('Cannot upload iterable with unknown size')
            data = ReadableIterator(data, size)

        # use requests-toolbelt multipart encoder to avoid reading
        # the full content of large files into memory
        menc = MultipartEncoder(fields={'file': ('file', data, content_type)})

        if callback is not None:
            menc = MultipartEncoderMonitor(menc, callback)

        headers = {'Content-Type': menc.content_type}

        if size:
            # latest version of requests requires str or bytes, not int
            if not isinstance(size, six.string_types):
                size = str(size)
            headers['Content-Length'] = size

        try:
            response = self.post(url, data=menc, headers=headers)
        except OverflowError:
            # Python __len__ uses integer so it is limited to system maxint,
            # and requests and requests-toolbelt use len() throughout.
            # This results in an overflow error when trying to upload a file
            # larger than system maxint (2GB on 32-bit OSes).
            # See http://bugs.python.org/issue12159
            msg = 'upload content larger than system maxint (32-bit OS limitation)'
            logger.error('OverflowError: %s', msg)
            raise OverflowError(msg)

        if response.status_code == requests.codes.accepted:
            return response.text.strip()

Example 22

Project: pysensu Source File: pysensu.py
    def delete_client(self, client):
        r = self._api_call("{}/clients/{}".format(self.api_url, client), "delete")
        if r.status_code != requests.codes.accepted:
            raise ValueError("Error deleting client ({})".format(r.status_code))

Example 23

Project: pysensu Source File: pysensu.py
Function: delete_event
    def delete_event(self, client, check):
        r = self._api_call("{}/events/{}/{}".format(self.api_url, client, check), "delete")
        if r.status_code != requests.codes.accepted:
            raise ValueError("Error deleting event ({})".format(r.status_code))