Python requests.patch() Examples

The following are code examples for showing how to use requests.patch(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: tintri-python-sdk   Author: Tintri   File: common.py    BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def _send_raw_http_request(self, method, url, data=None):
        self.__logger.debug('%s %s' % (method, url))
        if method in ['POST', 'PUT', 'PATCH']:
            self.__logger.log(TINTRI_LOG_LEVEL_DATA, 'Data: %s' % data)

        headers = {'content-type': 'application/json'}
        if self.__session_id:
            headers['cookie'] = 'JSESSIONID=%s' % self.__session_id

        if method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']:
            if method == 'GET': httpresp = requests.get(url, headers=headers, verify=False)
            elif method == 'POST': httpresp = requests.post(url, data, headers=headers, verify=False)
            elif method == 'PUT': httpresp = requests.put(url, data, headers=headers, verify=False)
            elif method == 'PATCH': httpresp = requests.patch(url, data, headers=headers, verify=False)
            elif method == 'DELETE': httpresp = requests.delete(url, headers=headers, verify=False)
            self._httpresp = httpresp # self._httpresp is for debugging only, not thread-safe
            return httpresp
        else:
            raise TintriError(None, message='Invalid HTTP method: ' + method) # This should never happen 
Example 2
Project: pyfirebase   Author: afropolymath   File: firebase.py    MIT License 6 votes vote down vote up
def run(self):
        try:
            self.sse = ClosableSSEClient(self.url)
            for msg in self.sse:
                event = msg.event
                if event is not None and event in ('put', 'patch'):
                    response = json.loads(msg.data)
                    if response is not None:
                        # Default to CHILD_CHANGED event
                        occurred_event = FirebaseEvents.CHILD_CHANGED
                        if response['data'] is None:
                            occurred_event = FirebaseEvents.CHILD_DELETED

                        # Get the event I'm trying to listen to
                        ev = FirebaseEvents.id(self.event_name)
                        if occurred_event == ev or ev == FirebaseEvents.CHILD_CHANGED:
                            self.callback(event, response)
        except socket.error:
            pass 
Example 3
Project: pylair   Author: lair-framework   File: client.py    MIT License 6 votes vote down vote up
def import_project(project, opts):
    u = opts.scheme + '://' + opts.host + _api + opts.project_id
    r = requests.patch(
            url=u,
            auth=HTTPBasicAuth(opts.username, opts.password),
            data=json.dumps(project),
            headers={'Content-Type': 'application/json'},
            verify=not (opts.insecure_skip_verify and opts.insecure_skip_verify))

    rjson = r.json()
    ret = dict(lair_response)
    ret['status'] = rjson['Status']
    ret['message'] = rjson['Message']

    return ret

# Function that performs project export. Returns a json string 
Example 4
Project: signals   Author: Amsterdam   File: update_category.py    Mozilla Public License 2.0 6 votes vote down vote up
def _update_category(self, signal_id, new_category_slug):
        endpoint = '{url}/v1/private/signals/{signal_id}'.format(url=self.url, signal_id=signal_id)
        data = json.dumps({
            'category': {
                'sub_category': new_category_slug,
                'text': MESSAGE,
            }
        })

        r = requests.patch(endpoint, data=data, headers=self.headers)
        if r.status_code == 200:
            print('Updated category for Signal #{}'.format(signal_id))
            self.success += 1
        else:
            print('Failed to update the category for Signal #{}'.format(signal_id))
            self.errors.append(signal_id) 
Example 5
Project: signals   Author: Amsterdam   File: close.py    Mozilla Public License 2.0 6 votes vote down vote up
def update_status(self, signal_id, new_state, message, acceptable_states=None):
        if acceptable_states is None:
            acceptable_states = []
        acceptable_states.append(new_state)  # if we are in desired state, skip

        # check status
        current_status = self._check_status(signal_id)
        if current_status['state'] in acceptable_states:
            print('Already in desired state.')
            return  # already in desired state

        # mutate signal status
        print('mutate')
        payload = copy.deepcopy(UPDATE_STATUS)
        payload['status']['state'] = new_state
        payload['status']['text'] = message

        response = requests.patch(
            DETAIL_ENDPOINT.format(base_url=self.base_url, signal_id=signal_id),
            json=payload,
            headers=self.headers,
        )
        response.raise_for_status()
        self._check_status(signal_id)
        print('') 
Example 6
Project: signals   Author: Amsterdam   File: reassign_ids_from_csv.py    Mozilla Public License 2.0 6 votes vote down vote up
def update_status(self, signal_id, new_state, message, acceptable_states=None):
        if acceptable_states is None:
            acceptable_states = []
        acceptable_states.append(new_state)  # if we are in desired state, skip

        # check status
        current_status = self._check_status(signal_id)
        if current_status['state'] in acceptable_states:
            print('Already in desired state.')
            return  # already in desired state

        # mutate signal status
        print('mutate')
        payload = copy.deepcopy(UPDATE_STATUS)
        payload['status']['state'] = new_state
        payload['status']['text'] = message

        response = requests.patch(
            DETAIL_ENDPOINT.format(base_url=self.base_url, signal_id=signal_id),
            json=payload,
            headers=self.headers,
        )
        response.raise_for_status()
        self._check_status(signal_id) 
Example 7
Project: signals   Author: Amsterdam   File: reassign_ids_from_csv.py    Mozilla Public License 2.0 6 votes vote down vote up
def update_category(self, signal_id, category_url, message):
        """
        Move given signal to category with descriptive message in logs.
        """
        category_data = self._check_category(signal_id)
        current_cat_url = urlparse(category_data['category_url']).path
        if current_cat_url == category_url:
            return

        payload = copy.deepcopy(UPDATE_CATEGORY)
        payload['category']['sub_category'] = category_url
        payload['category']['text'] = message
        print('mutate')
        response = requests.patch(
            DETAIL_ENDPOINT.format(base_url=self.base_url, signal_id=signal_id),
            json=payload,
            headers=self.headers,
        )
        response.raise_for_status()
        self._check_category(signal_id) 
Example 8
Project: pycloudflare-v4   Author: zmgit   File: api.py    MIT License 6 votes vote down vote up
def api_call_patch(self, uri, data='{}'):
        headers = {'X-Auth-Email': self.EMAIL, 'X-Auth-Key': self.TOKEN, 'Content-Type': 'application/json'}
        try:
            r = requests.patch(cf_api_url + uri, data=json.dumps(data), headers=headers)
        except (requests.ConnectionError,
                requests.RequestException,
                requests.HTTPError,
                requests.Timeout,
                requests.TooManyRedirects) as e:
            raise self.CONNError(str(e))
        try:
            api_result = json.loads(r.text)
        except ValueError:
            raise self.APIError('JSON parse failed.')
        if api_result['result'] == 'error':
            raise self.APIError(api_result['msg'])
        return api_result 
Example 9
Project: blue-team   Author: Sorsnce   File: amp_api.py    MIT License 6 votes vote down vote up
def patch(self, url, data):
        """PATCH method for amp."""
        try:
            response = requests.patch(
                "https://{}{}".format(self.endpoint, url),
                data=json.dumps(data),
                auth=(self.client_id, self.key),
                headers=self.headers
            )
            # Consider any status other than 2xx an error
            if not response.status_code // 100 == 2:
                return "Error: Unexpected response {}".format(response)
            try:
                return response.json()
            except:
                return "Error: Non JSON response {}".format(response.text)
        except requests.exceptions.RequestException as e:
            # A serious problem happened, like an SSLError or InvalidURL
            return "Error: {}".format(e) 
Example 10
Project: blue-team   Author: Sorsnce   File: amp_api.py    MIT License 6 votes vote down vote up
def patch(self, url, data):
        """PATCH method for amp."""
        try:
            response = requests.patch(
                "https://{}{}".format(self.endpoint, url),
                data=json.dumps(data),
                auth=(self.client_id, self.key),
                headers=self.headers
            )
            # Consider any status other than 2xx an error
            if not response.status_code // 100 == 2:
                return "Error: Unexpected response {}".format(response)
            try:
                return response.json()
            except:
                return "Error: Non JSON response {}".format(response.text)
        except requests.exceptions.RequestException as e:
            # A serious problem happened, like an SSLError or InvalidURL
            return "Error: {}".format(e) 
Example 11
Project: ibllib   Author: int-brain-lab   File: webclient.py    MIT License 6 votes vote down vote up
def patch(self, rest_query, data=None):
        """
        Sends a PATCH request to the Alyx server.
        For the dictionary contents, refer to:
        https://alyx.internationalbrainlab.org/docs

        :param rest_query: (required)the endpoint as full or relative URL
        :type rest_query: str
        :param data: json encoded string or dictionary
        :type data: None, dict or str

        :return: response object
        """
        if isinstance(data, dict):
            data = json.dumps(data)
        return self._generic_request(requests.patch, rest_query, data=data) 
Example 12
Project: ghpick   Author: shiqiyang-okta   File: engine.py    MIT License 6 votes vote down vote up
def __init__(self, username, password, org, repo, base_url=None):
        self.username = username
        self.password = password
        self.org = org
        self.repo = repo

        base_url = base_url or "https://api.github.com"
        self.base_url = "{}/repos/{}/{}".format(base_url, org, repo)

        # Endpoints
        self.diff_media_type = "application/vnd.github.3.diff"
        self.patch_media_type = "application/vnd.github.3.patch"
        self.contents_url = "{}/contents".format(self.base_url)
        self.merge_url = "{}/merges".format(self.base_url)
        self.compare_url = "{}/compare".format(self.base_url)
        self.trees_url = "{}/git/trees".format(self.base_url)
        self.refs_url = "{}/git/refs".format(self.base_url)
        self.blobs_url = "{}/git/blobs".format(self.base_url)
        self.commits_url = "{}/git/commits".format(self.base_url)
        self.repo_commits_url = "{}/commits".format(self.base_url) 
Example 13
Project: azure-apim-deployment-utils   Author: Haufe-Lexware   File: apim_core.py    Apache License 2.0 6 votes vote down vote up
def __update_property(self, base_url, sas_token, api_version, prop_name, prop_id, properties):
        prop_res = requests.patch(base_url + 'properties/' + prop_id + api_version,
                                  headers = {'Authorization': sas_token, 'If-Match': '*'},
                                  json = {
                                      'name': prop_name,
                                      'value': properties['value'],
                                      'tags': properties['tags'],
                                      'secret': properties['secret']    
                                  })
        if (200 != prop_res.status_code
            and 204 != prop_res.status_code):
            print "Update of property '" + prop_name + "' failed."
            print prop_res.text
            return False
        print "Successfully updated property '" + prop_name + "' (id " + prop_id + ")."
        return True 
Example 14
Project: azure-apim-deployment-utils   Author: Haufe-Lexware   File: token_factory.py    Apache License 2.0 6 votes vote down vote up
def get_scm_sas_token(self, instance):
        rest_token = self.get_sas_token(instance)
        
        git_access = requests.get(self.get_base_url(instance) + 'tenant/access/git' + self.get_api_version(), 
            headers = {'Authorization': rest_token})
        
        if (requests.codes.ok != git_access.status_code):
            return git_access.text
        
        git_data = byteify(json.loads(git_access.text))
        
        if not git_data['enabled']:
            print "Enabling git repository..."
            enable_res = requests.patch(self.get_base_url(instance) + 'tenant/access/git' + self.get_api_version(),
                                        headers = {'Authorization': rest_token},
                                        json = {'enabled': True})
            if (204 != enable_res.status_code):
                print "Failed to enable git access!"
                return False
            return self.get_scm_sas_token(instance)

        return urllib.quote_plus(self.get_sas_token_internal(git_data['id'], git_data['primaryKey'])) 
Example 15
Project: insightconnect-plugins   Author: rapid7   File: action.py    MIT License 6 votes vote down vote up
def run(self, params={}):
        user_principal_name = params.get(Input.USER_PRINCIPAL_NAME)
        location = params.get(Input.LOCATION)
        token = self.connection.access_token

        base_url = "https://graph.microsoft.com/v1.0/users/%s" % user_principal_name
        headers = {"Authorization": "Bearer %s" % token, "Content-Type": "application/json",}
        
        body = {
            "usageLocation": location
        }
        
        try:
            response = requests.patch(base_url, json=body, headers=headers)
        except requests.HTTPError:
            raise PluginException(cause=f"There was an issue updating the user's location. Double-check the user name: {user_principal_name}",
                        data=response.text)
        if response.status_code == 204:
            return {Output.SUCCESS: True}
        else:
            raise PluginException(f"The response from Office365 indicated something went wrong: {response.status_code}",
                              data=response.text) 
Example 16
Project: floyd-cli   Author: floydhub   File: tus_data.py    Apache License 2.0 6 votes vote down vote up
def _upload_chunk(self, data, offset, file_endpoint, headers=None, auth=None):
        floyd_logger.debug("Uploading %s bytes chunk from offset: %s", len(data), offset)

        h = {
            'Content-Type': 'application/offset+octet-stream',
            'Upload-Offset': str(offset),
            'Tus-Resumable': self.TUS_VERSION,
        }

        if headers:
            h.update(headers)

        response = requests.patch(file_endpoint, headers=h, data=data, auth=auth)
        self.check_response_status(response)

        return int(response.headers["Upload-Offset"]) 
Example 17
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def _patch(self, url, data_dict, params):
        rdata = json.dumps(data_dict)

        response = requests.patch(url, data=rdata, params=params,
                                  headers=self._headers)
        data = json.loads(response.content.decode())

        if response.status_code == 200:
            return data

        self.last_error = {
            "status_code": response.status_code,
            "detail": response.content
        }
        print(self.last_error)
        return None 
Example 18
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilder.py    MIT License 6 votes vote down vote up
def patch(self, restApi, data={}, silentMode=False):
        """
        Description
           A HTTP PATCH function to modify configurations.
        
        Parameters
           restApi: The REST API URL.
           data: The data payload for the URL.
           silentMode: True or False.  To display URL, data and header info.
        """

        if silentMode == False:
            print('\nPATCH:', restApi)
            print('DATA:', data)
            print('HEADERS:', self.jsonHeader)
        try:
            response = requests.patch(restApi, data=json.dumps(data), headers=self.jsonHeader)
            if silentMode == False:
                print('STATUS CODE:', response.status_code)
            if not re.match('2[0-9][0-9]', str(response.status_code)):
                print('\nPatch error:')
                raise IxNetRestApiException('http PATCH error: {0}\n'.format(response.text))
            return response
        except requests.exceptions.RequestException as errMsg:
            raise IxNetRestApiException('http PATCH error: {0}\n'.format(errMsg)) 
Example 19
Project: IxNetwork   Author: OpenIxia   File: IxNetRestApi.py    MIT License 6 votes vote down vote up
def configLicenseServerDetails(self, licenseServer=None, licenseMode=None, licenseTier=None):
        """
        Description
           Configure license server details: license server IP, license mode and license tier.

        Parameter
            licenseServer: License server IP address(s) in a list.
            licenseMode: subscription|perpetual}mixed
            licenseTier: tier1, tier2, tier3 ...

        Syntax
           PATCH: https://{apiServerIp}/api/v1/sessions/{id}/ixnetwork/globals/licensing
        """
        # Each new session requires configuring the new session's license details.
        data = {}
        if licenseServer:
            data.update({'licensingServers': licenseServer})
        if licenseMode:
            data.update({'mode': licenseMode})
        if licenseTier:
            data.update({'tier': licenseTier})

        response = self.patch(self.sessionUrl+'/globals/licensing', data=data)
        self.showLicenseDetails() 
Example 20
Project: IxNetwork   Author: OpenIxia   File: IxNetRestApi.py    MIT License 6 votes vote down vote up
def configMultivalue(self, multivalueUrl, multivalueType, data):
        """
        Description
            Configure multivalues.

        Parameters
            multivalueUrl: The multivalue href. Ex: /api/v1/sessions/1/ixnetwork/multivalue/1
            multivalueType: counter|singleValue|valueList
            data = In Python Dict format. Ex:
                   If singleValue, data={'value': '1.1.1.1'})
                   If valueList,   data needs to be in a [list]:  data={'values': [list]}
                   If counter,     data={'start': value, 'direction': increment|decrement, 'step': value}
        """
        if multivalueType == 'counter':
            # Example: macAddress = {'start': '00:01:01:00:00:01', 'direction': 'increment', 'step': '00:00:00:00:00:01'}
            #          data=macAddress)
            self.patch(self.httpHeader+multivalueUrl+'/counter', data=data)

        if multivalueType == 'singleValue':
            # data={'value': value}
            self.patch(self.httpHeader+multivalueUrl+'/singleValue', data=data)

        if multivalueType == 'valueList':
            # data={'values': ['item1', 'item2']}
            self.patch(self.httpHeader+multivalueUrl+'/valueList', data=data) 
Example 21
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilderRestApi.py    MIT License 6 votes vote down vote up
def patch(self, restApi, data={}, silentMode=False):
        """
        Description
           A HTTP PATCH function to modify configurations.
        
        Parameters
           restApi: The REST API URL.
           data: The data payload for the URL.
           silentMode: True or False.  To display URL, data and header info.
        """

        if silentMode == False:
            print('\nPATCH:', restApi)
            print('DATA:', data)
            print('HEADERS:', self.jsonHeader)
        try:
            response = requests.patch(restApi, data=json.dumps(data), headers=self.jsonHeader)
            if silentMode == False:
                print('STATUS CODE:', response.status_code)
            if not re.match('2[0-9][0-9]', str(response.status_code)):
                print('\nPatch error:')
                raise IxNetRestApiException('http PATCH error: {0}\n'.format(response.text))
            return response
        except requests.exceptions.RequestException as errMsg:
            raise IxNetRestApiException('http PATCH error: {0}\n'.format(errMsg)) 
Example 22
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilderRestApi.py    MIT License 6 votes vote down vote up
def patch(self, restApi, data={}, silentMode=False):
        """
        Description
           A HTTP PATCH function to modify configurations.
        
        Parameters
           restApi: The REST API URL.
           data: The data payload for the URL.
           silentMode: True or False.  To display URL, data and header info.
        """

        if silentMode == False:
            print('\nPATCH:', restApi)
            print('DATA:', data)
            print('HEADERS:', self.jsonHeader)
        try:
            response = requests.patch(restApi, data=json.dumps(data), headers=self.jsonHeader)
            if silentMode == False:
                print('STATUS CODE:', response.status_code)
            if not re.match('2[0-9][0-9]', str(response.status_code)):
                print('\nPatch error:')
                raise IxNetRestApiException('http PATCH error: {0}\n'.format(response.text))
            return response
        except requests.exceptions.RequestException as errMsg:
            raise IxNetRestApiException('http PATCH error: {0}\n'.format(errMsg)) 
Example 23
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilderRestApi.py    MIT License 6 votes vote down vote up
def patch(self, restApi, data={}, silentMode=False):
        """
        Description
           A HTTP PATCH function to modify configurations.
        
        Parameters
           restApi: The REST API URL.
           data: The data payload for the URL.
           silentMode: True or False.  To display URL, data and header info.
        """

        if silentMode == False:
            print('\nPATCH:', restApi)
            print('DATA:', data)
            print('HEADERS:', self.jsonHeader)
        try:
            response = requests.patch(restApi, data=json.dumps(data), headers=self.jsonHeader)
            if silentMode == False:
                print('STATUS CODE:', response.status_code)
            if not re.match('2[0-9][0-9]', str(response.status_code)):
                print('\nPatch error:')
                raise IxNetRestApiException('http PATCH error: {0}\n'.format(response.text))
            return response
        except requests.exceptions.RequestException as errMsg:
            raise IxNetRestApiException('http PATCH error: {0}\n'.format(errMsg)) 
Example 24
Project: example-turtlebot3   Author: RoboticBase   File: deploy_yaml.py    Apache License 2.0 6 votes vote down vote up
def main(args):
    if not os.path.isfile(args.yaml_path):
        raise FileNotFoundError(f'{args.yaml_path} does not exist')

    command = 'delete' if args.delete else 'apply'
    print(f'{command} {args.yaml_path} to {args.endpoint}')
    with open(args.yaml_path) as f:
        data = json.dumps(yaml.load(f))

    path = '/orion/v2/entities/' + args.entity_id + '/attrs?type=' + args.entity_type
    url = urllib.parse.urljoin(args.endpoint, path)
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'bearer {args.token}',
        'Fiware-Service': args.fiware_service,
        'Fiware-Servicepath': args.fiware_servicepath,
    }

    payload = {
        command: {
            'value': urllib.parse.quote(data)
        }
    }
    response = requests.patch(url, json=payload, headers=headers)
    print(f'status_code={response.status_code}, body={response.text}\n') 
Example 25
Project: koku   Author: project-koku   File: view.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def update(self, request, *args, **kwargs):
        """Update a Source."""
        if request.method == 'PUT':
            raise SourcesMethodException('PUT not supported')

        source_id = kwargs.get('source_id')
        url = f'{self.url}{source_id}/'
        try:
            r = requests.patch(url, json=request.data, headers=self.request.headers)
        except requests.exceptions.ConnectionError as error:
            raise SourcesProxyException(str(error))
        response = HttpResponse(
            content=r.content,
            status=r.status_code,
            content_type=r.headers['Content-Type']
        )

        return response 
Example 26
Project: koku   Author: project-koku   File: sources_http_client.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def set_source_status(self, error_msg, cost_management_type_id=None):
        """Set the source status with error message."""
        if not cost_management_type_id:
            cost_management_type_id = self.get_cost_management_application_type_id()

        application_query_url = '{}/applications?filter[application_type_id]={}&filter[source_id]={}'.\
            format(self._base_url, cost_management_type_id, str(self._source_id))
        application_query_response = requests.get(application_query_url, headers=self._identity_header)
        response_data = application_query_response.json().get('data')
        if response_data:
            application_id = response_data[0].get('id')

            application_url = f'{self._base_url}/applications/{str(application_id)}'
            if error_msg:
                status = 'unavailable'
            else:
                status = 'available'
                error_msg = ''
            json_data = {'availability_status': status, 'availability_status_error': str(error_msg)}
            application_response = requests.patch(application_url, json=json_data, headers=self._identity_header)
            if application_response.status_code != 204:
                raise SourcesHTTPClientError(f'Unable to set status for Source: {self._source_id}')
            return True
        return False 
Example 27
Project: pbl   Author: hassaku63   File: base.py    MIT License 6 votes vote down vote up
def patch(self, method, uri, query_param, request_param, headers, **kwargs):
        """
        TODO: Implementation.

        :param method:
        :param uri:
        :param query_param:
        :param request_param:
        :param headers:
        :param kwargs:
        :return:
        """
        _url = self.base_url + uri + "?" + urlencode(query_param)
        if headers is not None:
            resp = requests.ptach(_url, data=request_param, headers=headers, **kwargs)
        else:
            resp = requests.patch(_url, data=request_param, **kwargs)

        if resp.status_code == 200:
            return resp

        raise BacklogError("Http response {status}: {message}".format(status=resp.status_code, message=resp.text)) 
Example 28
Project: tng-cli   Author: sonata-nfv   File: policies.py    Apache License 2.0 6 votes vote down vote up
def define_policy_as_default(policy_uuid,service_uuid):
    """Define a Runtime Policy as default.

    :param policy_uuid: uuid of a policy descriptor.

    :returns: A tuple. [0] is a bool with the result. [1] is a string containing
        the uuid of the terminated policy descriptor.
    """

    url = env.policy_api + '/default/' + policy_uuid

    data = {'nsid': service_uuid, 'defaultPolicy': True}
    resp = requests.patch(url,
                          json=data,
                          timeout=env.timeout)
  
    if resp.status_code != 200:
        LOG.debug("Request returned with " + (str(resp.status_code)))
        error = resp.text
        return False, error

    message = json.loads(resp.text)['message']

    return True, message 
Example 29
Project: tng-cli   Author: sonata-nfv   File: policies.py    Apache License 2.0 6 votes vote down vote up
def attach_policy(policy_uuid, service_uuid, sla_uuid):
    """Attaches a policy to a service and SLA.

    :param policy_uuid: uuid of a policy descriptor.
    :param service_uuid: uuid of a network service.
    :param sla_uuid: uuid of an SLA.

    :returns: A tuple. [0] is a bool with the result. [1] is a string indicating
        the result.
    """

    data = {'nsid': service_uuid, 'slaid': sla_uuid}
    resp = requests.patch(env.policy_bind_api + '/' + policy_uuid,
                          json=data,
                          timeout=env.timeout)
  
    if resp.status_code != 200:
        LOG.debug("Request returned with " + (str(resp.status_code)))
        error = resp.text
        return False, error

    message = json.loads(resp.text)['message']

    return True, message 
Example 30
Project: ansible-f5   Author: joelwking   File: icontrol_install_config.py    MIT License 6 votes vote down vote up
def genericPATCH(self, body):
        """
           PATCH to edit an existing configuration object with a JSON body.
           Need to formulate the URL with the name as part of the URL and NAME must not be in the body
        """
        URI = "%s%s%s" % (BIG_IP.TRANSPORT, self.BIG_IP_host, self.uri)
        try:
            if self.token is None:
                r = requests.patch(URI, auth=(self.username, self.password), data=body, headers=BIG_IP.HEADER, verify=False)
            else:
                r = requests.patch(URI, data=body, headers=BIG_IP.HEADER, verify=False)
        except requests.ConnectionError as e:
            self.status_code = 599
            self.response = str(e)
            return None
        self.status_code = r.status_code
        try:
            self.response = r.json()
        except ValueError:
            self.response = None

        if r.status_code == 200:
            self.changed = True
            return True
        return False 
Example 31
Project: jumpserver-python-sdk   Author: jumpserver   File: request.py    GNU General Public License v2.0 5 votes vote down vote up
def patch(self, *args, **kwargs):
        kwargs['method'] = 'patch'
        return self.do(*args, **kwargs) 
Example 32
Project: pyfirebase   Author: afropolymath   File: firebase.py    MIT License 5 votes vote down vote up
def update(self, payload):
        return requests.patch(self.current_url, json=payload) 
Example 33
Project: salesforce-oauth2-REST-Metadata-API-Examples   Author: jctissier   File: REST_Api.py    MIT License 5 votes vote down vote up
def rest_api_patch(self, rest_url, body, api_version):
        """
        PATCH request to the REST API - Not tested
        :return: JSON string of the PATCH response
        """
        response = requests.patch(
            "{org_instance}/services/data/v{api_version}/{rest_url}".format(
                org_instance=self.instance, api_version=api_version, rest_url=rest_url
            ),
            data=body,
            headers=self.sf_headers
        )

        return response 
Example 34
Project: sanic   Author: huge-success   File: release.py    MIT License 5 votes vote down vote up
def _tag_release(new_version, current_version, milestone, release_name, token):
    global GIT_COMMANDS
    global RELEASE_NOTE_UPDATE_URL
    for command_name in ["create_new_tag", "push_tag"]:
        command = GIT_COMMANDS.get(command_name)
        command[0] = command[0].format(
            new_version=new_version, current_version=current_version
        )
        out, error, ret = _run_shell_command(command=command)
        if int(ret) != 0:
            print("Failed to execute the command: {}".format(command[0]))
            exit(1)

    change_log = _generate_markdown_document(
        milestone, release_name, current_version, new_version
    )

    body = {"name": release_name or new_version, "body": change_log}

    headers = {"content-type": "application/json"}

    response = patch(
        RELEASE_NOTE_UPDATE_URL.format(new_version=new_version, token=token),
        data=dumps(body),
        headers=headers,
    )
    response.raise_for_status() 
Example 35
Project: fxosREST   Author: kaisero   File: fxos.py    GNU General Public License v3.0 5 votes vote down vote up
def _patch(self, request, data, headers=None):
        url = '{0}{1}'.format(self._url(), request)
        headers = self.headers if headers is None else headers
        response = requests.patch(url, data=json.dumps(data), headers=headers, verify=self.verify_cert,
                                  timeout=self.timeout)
        return self._validate(response) 
Example 36
Project: foxtrot   Author: dsnezhkov   File: records.py    MIT License 5 votes vote down vote up
def precord(payload):
    # r = requests.patch(uri, data=json.dumps(payload), headers=headers)
    # For bypassing self-signed verification
    r = requests.patch(zone_uri, data=json.dumps(payload), headers=headers, verify=False)
    print(r.text) 
Example 37
Project: powerdns-shell-wrapper   Author: opensource-expert   File: pdns_zone.py    GNU General Public License v3.0 5 votes vote down vote up
def exec_pdns_api(self, action, url, json_data=None, text=False):

        # remove double: //
        url = url.replace(r'//', '/')
        # remove extra ^/
        if url[0] == '/':
            url = url[1:]

        call_url = self.url_base + '/' + url

        headers = {'X-API-Key': self.key} 

        if action == 'GET':
            r = requests.get(call_url, headers=headers)
        elif action == 'POST':
            r = requests.post(call_url, data=json_data, headers=headers)
        elif action == 'PATCH':
            r = requests.patch(call_url, data=json_data, headers=headers)
        elif action == 'DELETE':
            r = requests.delete(call_url, headers=headers)
        else:
            raise ValueError('action unknown: %s' % action)

        if r.ok:
            if action == 'GET':
                if text:
                    return r.text
                else:
                    return r.json()
            else:
                return r
        else:
            raise ValueError('url returned an error: %s:\n%s\n---\n%s' % (call_url, r.headers, r.text)) 
Example 38
Project: lightweight-rest-tester   Author: ridi   File: __init__.py    MIT License 5 votes vote down vote up
def _send_request(method, url, params, data, **settings):
        if method == TestMethod.GET:
            return requests.get(url=url, params=params, **settings)
        elif method == TestMethod.PUT:
            return requests.put(url=url, data=data, **settings)
        elif method == TestMethod.POST:
            return requests.post(url=url, data=data, **settings)
        elif method == TestMethod.PATCH:
            return requests.patch(url=url, data=data, **settings)
        elif method == TestMethod.DELETE:
            return requests.delete(url=url, **settings)
        else:
            raise UnsupportedMethodError('Unsupported method: %s' % method) 
Example 39
Project: tinycards-python-api   Author: floscha   File: rest_api.py    MIT License 5 votes vote down vote up
def update_deck(self, deck, user_id):
        """Update an existing deck.

        Args:
            deck (Deck): The Deck object to update.

        Returns:
            Deck: The updated Deck object if update was successful.

        """
        # Clone headers to not modify the global variable.
        headers = dict(DEFAULT_HEADERS)
        if deck.cover:
            # A new cover has been set on the deck, send the PATCH request as a
            # multipart-form:
            request_payload = json_converter.deck_to_json(deck)
            request_payload = to_multipart_form(request_payload)
            headers['Content-Type'] = request_payload.content_type
        else:
            # Otherwise, send the PATCH request as JSON:
            request_payload = json_converter.deck_to_json(deck,
                                                          as_json_str=True)
            request_payload = json.dumps(request_payload)
            headers['Content-Type'] = 'application/json'

        r = requests.patch(url=API_URL + 'decks/' + deck.id,
                           data=request_payload, headers=headers,
                           cookies={'jwt_token': self.jwt})

        if not r.ok:
            raise Exception('Failure while sending updates to server: %s'
                            % r.text)

        # The response from the PATCH request does not contain cards.
        # Therefore, we have to query the updated deck with an extra request.
        updated_deck = self.get_deck(deck.id, user_id)

        return updated_deck 
Example 40
Project: automated_bgp_iox   Author: bigevilbeard   File: iosxerestapi.py    MIT License 5 votes vote down vote up
def _execute_call(self, url, method='get', data=None):
        try:
            self.logger.info('Calling {}'.format(url))
            requests.packages.urllib3.disable_warnings()
            url_base = 'https://{0}:{1}/restconf/data/'.format(self.host, self.port)
            headers = {
            'Accept': 'application/yang-data+json',
            'content-type': 'application/yang-data+json'
            }
            if method == 'get':
                response = requests.get(url_base+url, auth=(self.username, self.password), headers=headers, verify=False)
            elif method == 'patch':
                response = requests.patch(url_base+url, auth=(self.username, self.password), headers=headers, verify=False, data=json.dumps(data, ensure_ascii=False))
            elif method == 'delete':
                response = requests.delete(url_base+url, auth=(self.username, self.password), headers=headers, verify=False, data=json.dumps(data, ensure_ascii=False))

            result = Result(response=response)
            result.status_code = response.status_code

            if response.status_code in HTTP_ERROR_CODES:
                result.ok = False
                result.error = HTTP_ERROR_CODES[response.status_code]

            elif response.status_code in HTTP_SERVER_ERRORS:
                result.ok = False
                result.error = HTTP_SERVER_ERRORS[response.status_code]

            elif response.status_code in HTTP_SUCCESS_CODES:
                result.ok = True
                result.message = HTTP_SUCCESS_CODES[response.status_code]

            if not response.status_code == 204:
                result.json = response.json()

            return result

                #response = requests.get(url, auth=(USER, PASS), headers=headers, verify=False)
        except Exception as e:
            self.logger.error(e) 
Example 41
Project: automated_bgp_iox   Author: bigevilbeard   File: iosxerestapi.py    MIT License 5 votes vote down vote up
def add_access_group(self, interface):
        """Function to create a IP accessgroup on IOS XE"""
        parsed_interface =re.search(r"(?P<intrfname>[A-Za-z]+)(?P<intf_num>\d((/\d+)+(\.\d+)?)|\d)",interface).groupdict()
        interface_name = parsed_interface.get('intrfname')
        interface_number = parsed_interface.get('intf_num')
        api_interface = '{0}={1}'.format(interface_name, interface_number)
        url = 'https://{0}:{1}/data/Cisco-IOS-XE-native:native/interface/{2}'.format(self.host, self.port, api_interface)
        headers = {
        'Accept': 'application/yang-data+json',
        'content-type': 'application/yang-data+json'
        }

        data = {
        "Cisco-IOS-XE-native:GigabitEthernet":[
              {
                 "name":interface_number,
                 "ip":{
                    "access-group":{
                       "in":{
                          "acl":{
                             "acl-name":"DROP",
                             "in":[None]
                          }
                       }
                    }
                 }
              }
           ]
        }

        response = self._execute_call('Cisco-IOS-XE-native:native/interface/{0}'.format(api_interface), method='patch', data=data)
        return response 
Example 42
Project: godaddypy   Author: eXamadeus   File: client.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _patch(self, url, json=None, **kwargs):
        return self._request_submit(requests.patch, url=url, json=json, **kwargs) 
Example 43
Project: openeo-qgis-plugin   Author: Open-EO   File: connect.py    Apache License 2.0 5 votes vote down vote up
def patch(self, path):
        """
        Makes a RESTful PATCH request to the back end.
        :param path: URL of the request (without root URL e.g. "/data")
        :return: response: Response
        """
        auth_header = self.get_header()
        auth = self.get_auth()
        return requests.patch(self._url+path, headers=auth_header, auth=auth, timeout=5) 
Example 44
Project: blue-team   Author: Sorsnce   File: rest_methods.py    MIT License 5 votes vote down vote up
def patch(url,data):
	try:
	    response = requests.patch(url, data)
	    # Consider any status other than 2xx an error
	    if not response.status_code // 100 == 2:
	        return "Error: Unexpected response {}".format(response)
	    try:
	        return response.json()
	    except:
	        return "Error: Non JSON response {}".format(response.text)
	except requests.exceptions.RequestException as e:
	    # A serious problem happened, like an SSLError or InvalidURL
	    return "Error: {}".format(e) 
Example 45
Project: blue-team   Author: Sorsnce   File: rest_methods.py    MIT License 5 votes vote down vote up
def patch(url, headers, data):
    try:
        response = requests.patch(url, json.dumps(data), headers=headers, verify=True)
        # Consider any status other than 2xx an error
        if not response.status_code // 100 == 2:
            return "Error: Unexpected response {}".format(response)
        try:
            return response.json()
        except:
            return "Error: Non JSON response {}".format(response.text)
    except requests.exceptions.RequestException as e:
        # A serious problem happened, like an SSLError or InvalidURL
        return "Error: {}".format(e) 
Example 46
Project: blue-team   Author: Sorsnce   File: rest_methods.py    MIT License 5 votes vote down vote up
def amppatch(url, headers, data):
	try:
		response = requests.patch(url, json.dumps(data), headers=headers, verify=True)
		# Consider any status other than 2xx an error
		if not response.status_code // 100 == 2:
			return "Error: Unexpected response {}".format(response)
		try:
			return response.json()
		except:
			return "Error: Non JSON response {}".format(response.text)
	except requests.exceptions.RequestException as e:
		# A serious problem happened, like an SSLError or InvalidURL
		return "Error: {}".format(e) 
Example 47
Project: phpIPAM   Author: michaelluich   File: phpIPAM.py    GNU General Public License v3.0 5 votes vote down vote up
def address_update(self, ip, hostname=None, description=None, is_gateway=None, mac=None):
        """Update address informations"""
        orgdata = self.address_search(ip)[0]
        data = {}
        if hostname != None: data["hostname"] = hostname
        if description != None: data["description"] = description
        if is_gateway != None: data["is_gateway"] = is_gateway
        if mac != None: data["mac"] = mac
        return self.__query("/addresses/%s/"%orgdata['id'], method=requests.patch, data=data) 
Example 48
Project: pyweed   Author: iris-edu   File: redmine_to_github.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def close(self, issue_number):
        """
        Close an issue
        """
        edit_issue_url = "%s/%s" % (self.issues_url, issue_number)
        r = requests.patch(
            edit_issue_url,
            json={
                "state": "closed",
            },
            headers=self.headers,
        )
        r.raise_for_status() 
Example 49
Project: SalesforcePy   Author: forcedotcom   File: commons.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def patch_request(base_request):
    """
    Performs PATCH request for the class provided.

    :param: base_request: Class with which to make request.
    :type: BaseRequest
    :return: response
    :rtype: requests.Response
    """
    (headers, _, _, _, service) = base_request.get_request_vars()

    return requests.patch(
        service, headers=headers, proxies=base_request.proxies, timeout=base_request.timeout,
        json=base_request.request_body) 
Example 50
Project: ghpick   Author: shiqiyang-okta   File: engine.py    MIT License 5 votes vote down vote up
def _patch(self, url, data=None):
        """ Abstract the requests.patch call """
        payload = self._make_payload(data)

        response = requests.patch(url,
            data=payload,
            auth=(self.username, self.password),
            verify=False)
        self._validate_response(response)
        item = response.json()

        return item 
Example 51
Project: netbox_automation   Author: JNPRAutomate   File: configure_netbox.py    MIT License 5 votes vote down vote up
def enable_management_ip_address():
    for item in my_variables_in_yaml['management_addresses']:
     if item['mgmt_only']==True:
      device_id=get_device_id(item['device'])
      interface_id=get_interface_id(item['interface'], item['device'])
      address_id=get_address_id((item['device']), interface_id)
      url=url_base + 'api/dcim/devices/' + str(device_id) + '/'
      payload={
          "primary_ip4": address_id
      }
      rest_call = requests.patch(url, headers=headers, data=json.dumps(payload)) 
Example 52
Project: challenges_with-network_automation   Author: bigevilbeard   File: iosxerestapi.py    MIT License 5 votes vote down vote up
def _execute_call(self, url, method='get', data=None):
        try:
            self.logger.info('Calling {}'.format(url))
            requests.packages.urllib3.disable_warnings()
            url_base = 'https://{0}:{1}/restconf/data/'.format(self.host, self.port)
            headers = {
            'Accept': 'application/yang-data+json',
            'content-type': 'application/yang-data+json'
            }
            if method == 'get':
                response = requests.get(url_base+url, auth=(self.username, self.password), headers=headers, verify=False)
            elif method == 'patch':
                response = requests.patch(url_base+url, auth=(self.username, self.password), headers=headers, verify=False, data=json.dumps(data, ensure_ascii=False))
            elif method == 'delete':
                response = requests.delete(url_base+url, auth=(self.username, self.password), headers=headers, verify=False, data=json.dumps(data, ensure_ascii=False))

            result = Result(response=response)
            result.status_code = response.status_code

            if response.status_code in HTTP_ERROR_CODES:
                result.ok = False
                result.error = HTTP_ERROR_CODES[response.status_code]

            elif response.status_code in HTTP_SERVER_ERRORS:
                result.ok = False
                result.error = HTTP_SERVER_ERRORS[response.status_code]

            elif response.status_code in HTTP_SUCCESS_CODES:
                result.ok = True
                result.message = HTTP_SUCCESS_CODES[response.status_code]

            if not response.status_code == 204:
                result.json = response.json()

            return result

                #response = requests.get(url, auth=(USER, PASS), headers=headers, verify=False)
        except Exception as e:
            self.logger.error(e) 
Example 53
Project: challenges_with-network_automation   Author: bigevilbeard   File: iosxerestapi.py    MIT License 5 votes vote down vote up
def add_access_group(self, interface):
        """Function to create a IP accessgroup on IOS XE"""
        parsed_interface =re.search(r"(?P<intrfname>[A-Za-z]+)(?P<intf_num>\d((/\d+)+(\.\d+)?)|\d)",interface).groupdict()
        interface_name = parsed_interface.get('intrfname')
        interface_number = parsed_interface.get('intf_num')
        api_interface = '{0}={1}'.format(interface_name, interface_number)
        url = 'https://{0}:{1}/data/Cisco-IOS-XE-native:native/interface/{2}'.format(self.host, self.port, api_interface)
        headers = {
        'Accept': 'application/yang-data+json',
        'content-type': 'application/yang-data+json'
        }

        data = {
        "Cisco-IOS-XE-native:GigabitEthernet":[
              {
                 "name":interface_number,
                 "ip":{
                    "access-group":{
                       "in":{
                          "acl":{
                             "acl-name":"DROP",
                             "in":[None]
                          }
                       }
                    }
                 }
              }
           ]
        }

        response = self._execute_call('Cisco-IOS-XE-native:native/interface/{0}'.format(api_interface), method='patch', data=data)
        return response 
Example 54
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilder.py    MIT License 5 votes vote down vote up
def ixVmConfigCardId(self, cardName=None, mgmtIp='', keepAlive=300):
        """
        Description
           Add/Configure a virtual line card.

        Syntax
           http://{apiServerIp:11009}/availableHardware/virtualChassis/ixVmCard

        Parameters
           cardId:   The cardId.  Must begin with 1 and in sequential order.
           cardName: Optional: Specify a name for the card.
           mgmtIp:   The virtual line card's management IP address.
           keepAlive: Integer in seconds
        """
        url = self.sessionUrl+'/availableHardware/virtualChassis/ixVmCard'
        nextCardId = self.ixVmGetLastCardId()+1
        data = {"cardId": str(nextCardId),
                "managementIp": str(mgmtIp),
                "keepAliveTimeout": int(keepAlive)
                }
        response = self.post(url, data=data, ignoreError=True)
        if response.status_code == 400:
            print()
            for error in response.json()['errors']:
                print('\t', error['detail'])
            raise IxNetRestApiException
        
        if cardName is not None:
            self.patch(url, data={'cardName': cardName})

        ixVmCardObj = response.json()['links'][0]['href']
        return ixVmCardObj 
Example 55
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilder.py    MIT License 5 votes vote down vote up
def ixVmConfigPortId(self, cardUrl, portName=None, promiscuousMode='false', mtu='1500'):
        """
        Description
            Add/Configure a virtual port to the cardId.
        
        Parameters
            cardUrl:    The cardId object: /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/1
            interface:  eth1|eth2|eth3 ...
            portId:     Optional: The portId. Must begin with 1. Warning! You will have a misconfiguration if you don't begin with ID 1.
            portName:   Optional: Specify the name of the virtual port.
            promiscuousMode: true|false
            mtu:        Optional: The MTU frame size.
        """
        url = self.httpHeader+cardUrl+'/ixVmPort'
        portId = self.ixVmGetLastPortId(cardUrl)
        interface = 'eth'+str(portId)
        data = {'interface': interface,
                'portId': str(portId),
                'promiscMode': str(promiscuousMode),
                'mtu': str(mtu),
                }
        response = self.post(url, data=data)
        # /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/2/ixVmPort/1
        if portName is not None:
            self.patch(url, data={'portName': portName})

        return response.json()['links'][0]['href'] 
Example 56
Project: IxNetwork   Author: OpenIxia   File: IxNetRestLoadQuickTestConfig.py    MIT License 5 votes vote down vote up
def setAttribute(self,objRef,name,value):
		if self.srvUrl not in objRef:
			objRef = self.srvUrl + objRef
		name=name.lstrip("-")
		if debug:print "SET ATTRIBUTE DATA",{name:value}
		try:self.response = requests.patch(url=objRef, data=json.dumps({name:value}), headers=self.urlHeadersJson)
		except Exception, e:raise Exception('Got an error code: ', e)  
		self.checkError() 
Example 57
Project: IxNetwork   Author: OpenIxia   File: IxNetRestApi.py    MIT License 5 votes vote down vote up
def patch(self, restApi, data={}, silentMode=False):
        """
        Description
           A HTTP PATCH function to modify configurations.

        Parameters
           restApi: The REST API URL.
           data: The data payload for the URL.
           silentMode: True or False.  To display URL, data and header info.
        """

        if silentMode == False:
            self.logInfo('\nPATCH: %s' % restApi)
            self.logInfo('DATA: %s' % data)
            self.logInfo('HEADERS: %s' % self.jsonHeader)

        try:
            response = requests.patch(restApi, data=json.dumps(data), headers=self.jsonHeader, verify=self.verifySslCert)
            if silentMode == False:
                print('STATUS CODE:', response.status_code)
            if not re.match('2[0-9][0-9]', str(response.status_code)):
                if 'message' in response.json() and response.json()['messsage'] != None:
                    self.logWarning('\n%s' % response.json()['message'])
                self.showErrorMessage()
                raise IxNetRestApiException('PATCH error: {0}\n'.format(response.text))
            return response
        except requests.exceptions.RequestException as errMsg:
            raise IxNetRestApiException('PATCH error: {0}\n'.format(errMsg)) 
Example 58
Project: IxNetwork   Author: OpenIxia   File: IxNetRestApi.py    MIT License 5 votes vote down vote up
def linuxServerConfigGlobalLicenseServer(self, linuxServerIp, licenseServerIp, licenseMode, licenseTier):
        """
        Description
           On a new Linux API Linux installation, you need to set the global license server once.
           When a new session is created, it will check the global license settings and config the
           license settings on the new session.

        Parameters
            linuxServerIp: IP address of the Linux API server.
            licenseServerIp: Type = list. [IP address of the license server]
            licenseMode: subscription, perpetual or mixed
            licenseier: tier1, tier2, tier3

        Syntax
           PATCH: https://<apiServerIp>/api/v1/sessions/9999/ixnetworkglobals/license
           DATA:  {'servers': list(licenseServerIp),
                   'mode': str(licenseMode),
                   'tier': str(licenseTier)
                  }
        """

        staticUrl = 'https://{linuxServerIp}/api/v1/sessions/9999/ixnetworkglobals/license'.format(linuxServerIp=linuxServerIp)
        self.logInfo('\nlinuxServerConfigGlobalLicenseServer:\n\t{0}\n\t{1}\n\t{2}\n'. format(licenseServerIp,
                                                                                       licenseMode,
                                                                                       licenseTier))
        response = self.patch(staticUrl, data={'servers': [licenseServerIp], 'mode': licenseMode, 'tier': licenseTier})
        response = self.get(staticUrl)
        licenseServerIp = response.json()['servers'][0]
        licenseServerMode = response.json()['mode']
        licenseServerTier = response.json()['tier']
        self.logInfo('\nLinuxApiServer static license server:')
        self.logInfo('\t', licenseServerIp)
        self.logInfo('\t', licenseServerMode)
        self.logInfo('\t', licenseServerTier) 
Example 59
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilderRestApi.py    MIT License 5 votes vote down vote up
def ixVmConfigPortId(self, cardUrl, portName=None, promiscuousMode='false', mtu='1500'):
        """
        Description
            Add/Configure a virtual port to the cardId.
        
        Parameters
            cardUrl:    The cardId object: /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/1
            interface:  eth1|eth2|eth3 ...
            portId:     Optional: The portId. Must begin with 1. Warning! You will have a misconfiguration if you don't begin with ID 1.
            portName:   Optional: Specify the name of the virtual port.
            promiscuousMode: true|false
            mtu:        Optional: The MTU frame size.
        """
        url = self.httpHeader+cardUrl+'/ixVmPort'
        portId = self.ixVmGetLastPortId(cardUrl)
        interface = 'eth'+str(portId)
        data = {'interface': interface,
                'portId': str(portId),
                'promiscMode': str(promiscuousMode),
                'mtu': str(mtu),
                }
        response = self.post(url, data=data)
        # /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/2/ixVmPort/1
        if portName is not None:
            self.patch(url, data={'portName': portName})

        return response.json()['links'][0]['href'] 
Example 60
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilderRestApi.py    MIT License 5 votes vote down vote up
def ixVmConfigPortId(self, cardUrl, portName=None, promiscuousMode='false', mtu='1500'):
        """
        Description
            Add/Configure a virtual port to the cardId.
        
        Parameters
            cardUrl:    The cardId object: /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/1
            interface:  eth1|eth2|eth3 ...
            portId:     Optional: The portId. Must begin with 1. Warning! You will have a misconfiguration if you don't begin with ID 1.
            portName:   Optional: Specify the name of the virtual port.
            promiscuousMode: true|false
            mtu:        Optional: The MTU frame size.
        """
        url = self.httpHeader+cardUrl+'/ixVmPort'
        portId = self.ixVmGetLastPortId(cardUrl)
        interface = 'eth'+str(portId)
        data = {'interface': interface,
                'portId': str(portId),
                'promiscMode': str(promiscuousMode),
                'mtu': str(mtu),
                }
        response = self.post(url, data=data)
        # /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/2/ixVmPort/1
        if portName is not None:
            self.patch(url, data={'portName': portName})

        return response.json()['links'][0]['href'] 
Example 61
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilderRestApi.py    MIT License 5 votes vote down vote up
def ixVmConfigPortId(self, cardUrl, portName=None, promiscuousMode='false', mtu='1500'):
        """
        Description
            Add/Configure a virtual port to the cardId.
        
        Parameters
            cardUrl:    The cardId object: /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/1
            interface:  eth1|eth2|eth3 ...
            portId:     Optional: The portId. Must begin with 1. Warning! You will have a misconfiguration if you don't begin with ID 1.
            portName:   Optional: Specify the name of the virtual port.
            promiscuousMode: true|false
            mtu:        Optional: The MTU frame size.
        """
        url = self.httpHeader+cardUrl+'/ixVmPort'
        portId = self.ixVmGetLastPortId(cardUrl)
        interface = 'eth'+str(portId)
        data = {'interface': interface,
                'portId': str(portId),
                'promiscMode': str(promiscuousMode),
                'mtu': str(mtu),
                }
        response = self.post(url, data=data)
        # /api/v1/sessions/1/ixnetwork/availableHardware/virtualChassis/ixVmCard/2/ixVmPort/1
        if portName is not None:
            self.patch(url, data={'portName': portName})

        return response.json()['links'][0]['href'] 
Example 62
Project: edx-video-worker   Author: edx   File: api_communicate.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def send_veda_status(self):
        """
        VEDA Stati (as of 05-2016) [salient only to NODE],
        kept in 'globals'
        ----
        'Active Transcode'
        ----
        * This will update a video's status
        """
        for u in self.veda_video_dict:
            """
            This should just send transcode_active, as the other queue
            phases are controlled by other big veda pipeline steps
            """
            if self.VideoObject.valid is not True:
                return None
            video_data = {'video_trans_status': self.veda_video_status}

            w = requests.patch(
                '/'.join((settings['veda_api_url'], 'videos', str(u['id']), '')),
                headers=self.veda_headers,
                data=json.dumps(video_data)
            )
            if w.status_code != 200:

                logger.error('VEDA API: GET Failure, no objects') 
Example 63
Project: docker-service-registrator-kong   Author: mvanholsteijn   File: registrator.py    Apache License 2.0 5 votes vote down vote up
def sync_apis(self, apis):
        """
        synchronizes the API definition defined on this machine with Kong.
        """
        self.load_apis()
        for name in apis:
            definition = apis[name]
            if name in self.apis:
                                # api with the same name already exists, check
                                # for update
                current = self.apis[name]
                differences = diff(current, definition, syntax='explicit')
                has_update = filter(lambda k: k.label == 'update', differences.keys())
                if len(has_update) > 0:
                    log.info('updating API definition %s.', name)
                    r = requests.patch(
                        '%s/apis/%s' % (self.admin_url, name),
                        json=definition, verify=self.verify_ssl)
                    if r.status_code == 200 or r.status_code == 201:
                        self.apis[name] = r.json()
                    else:
                        log.error('failed to update %s at %s, %s',
                                  name, self.admin_url, r.text)
                else:
                    log.info('API definition %s is up-to-date.', name)
            else:
                log.info('creating API definition %s.', name)
                r = requests.put('%s/apis/' % self.admin_url,
                                 json=definition, verify=self.verify_ssl)
                if r.status_code == 200 or r.status_code == 201:
                    self.apis[name] = r.json()
                else:
                    log.error('failed to create %s at %s, %s',
                              name, self.admin_url, r.text) 
Example 64
Project: koku   Author: project-koku   File: create_sources.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def create_s3_bucket(self, parameters, billing_source):
        json_data = {'billing_source': {'bucket': billing_source}}

        url = '{}/{}/'.format(self._base_url, parameters.get('source_id'))
        response = requests.patch(url, headers=self._identity_header, json=json_data)
        return response 
Example 65
Project: koku   Author: project-koku   File: create_sources.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def create_azure_storage(self, parameters, resource_group, storage_account):
        json_data = {'billing_source': {'data_source': {'resource_group': resource_group,
                                                        'storage_account': storage_account}}}

        url = '{}/{}/'.format(self._base_url, parameters.get('source_id'))
        response = requests.patch(url, headers=self._identity_header, json=json_data)
        return response 
Example 66
Project: koku   Author: project-koku   File: create_sources.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def create_azure_subscription_id(self, parameters, subscription_id):
        json_data = {'authentication': {'credentials': {'subscription_id': subscription_id}}}

        url = '{}/{}/'.format(self._base_url, parameters.get('source_id'))
        response = requests.patch(url, headers=self._identity_header, json=json_data)
        return response 
Example 67
Project: vibe   Author: 3ll3d00d   File: httpclient.py    MIT License 5 votes vote down vote up
def patch(self, url, **kwargs):
        """
        sends a patch.
        :param url:  the url to send to.
        :param kwargs: the args.
        :return:
        """
        pass 
Example 68
Project: vibe   Author: 3ll3d00d   File: httpclient.py    MIT License 5 votes vote down vote up
def patch(self, url, **kwargs):
        try:
            return requests.patch(url, timeout=0.5, **kwargs)
        except requests.exceptions.RequestException as e:
            raise RequestException("Unable to PATCH " + url) from e 
Example 69
Project: vibe   Author: 3ll3d00d   File: httpclient.py    MIT License 5 votes vote down vote up
def patch(self, url, **kwargs):
        self.record.append(('patch', url, kwargs))
        return self._resp() 
Example 70
Project: pbl   Author: hassaku63   File: base.py    MIT License 5 votes vote down vote up
def invoke_method(self, method, uri, query_param={}, request_param={}, headers=None, **kwargs):
        """
        Delegate requests to get/post/delete method.
        Each method implements by any http client, default client is requests.

        :param method: HTTP Method. supports GET/POST/DELETE
        :param uri: API Endpoint. 'uri' expects a URI excluded '/api/v2/' prefix
        :param query_param: dict of URL parameter. this will be url-encoded string
        :param request_param: dict of body parameter. this will use when invoke post request
        :param headers: HTTP Header dict. Recommend value is None. if None, then use default implements of http client(requests).
        :return: http response object
        """
        query_param.setdefault("apiKey", self.api_key)

        method = method.lower()

        if method == "get":
            resp = self.get(method, uri, query_param, request_param, headers, **kwargs)

        elif method == "post":
            resp = self.post(method, uri, query_param, request_param, headers, **kwargs)

        elif method == "delete":
            resp = self.delete(method, uri, query_param, request_param, headers, **kwargs)

        elif method == "patch":
            resp = self.patch(method, uri, query_param, request_param, headers, **kwargs)

        else:
            raise BacklogError("Not supported http method: {}".format(method))

        return resp 
Example 71
Project: pbl   Author: hassaku63   File: base.py    MIT License 5 votes vote down vote up
def patch(self, method, uri, query_param, request_param, headers, **kwargs):
        raise NotImplementedError 
Example 72
Project: MongoDB-Atlas-API   Author: jdrumgoole   File: apimixin.py    Apache License 2.0 5 votes vote down vote up
def atlas_patch(self, resource, data):
        self._log.debug(f"atlas_patch({resource}, {data})")
        return self.patch(f"{self.ATLAS_BASE_URL}{resource}", data) 
Example 73
Project: MongoDB-Atlas-API   Author: jdrumgoole   File: apimixin.py    Apache License 2.0 5 votes vote down vote up
def patch(self, resource, patch_doc):
        try:
            p = requests.patch(f"{resource}",
                               json=patch_doc,
                               headers=self.ATLAS_HEADERS,
                               auth=self._auth
                               )
            p.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise AtlasPatchError(e, p.json())
        return p.json() 
Example 74
Project: IAIbot   Author: SincereXIA   File: requests.py    MIT License 5 votes vote down vote up
def patch(url, data=None, **kwargs) -> AsyncResponse:
    return AsyncResponse(
        await run_sync_func(requests.patch, url=url, data=data, **kwargs)) 
Example 75
Project: victoropspy   Author: estecker   File: Incidents.py    The Unlicense 5 votes vote down vote up
def ack_user(self, username):
        """ This will ack any incident assigned to you, even if the incident is already acked"""
        body = {"userName": username, "message": "Acked via victoropspy"}
        r = requests.patch(self.api_base_url + '/api-public/v1/incidents/byUser/ack', headers=self.headers, json=body)
        if r.ok and r.json()['results']:
            logging.info("Acknowledged these incidents:")
            for i in r.json()['results']:
                logging.info(i)
        else:
            logging.info("Nothing happened. Are there any incidents assigned to {}?".format(username)) 
Example 76
Project: django-outlook-api   Author: spectrumone   File: outlookservice.py    MIT License 4 votes vote down vote up
def make_api_call(method, url, token, payload = None, parameters = None):
    # Send these headers with all API calls
    headers = { 'User-Agent' : 'django-tutorial/1.0',
                'Authorization' : 'Bearer {0}'.format(token),
                'Accept' : 'application/json'}

    # Use these headers to instrument calls. Makes it easier
    # to correlate requests and responses in case of problems
    # and is a recommended best practice.
    request_id = str(uuid.uuid4())
    instrumentation = { 'client-request-id' : request_id,
                        'return-client-request-id' : 'true' }

    headers.update(instrumentation)

    response = None 

    payload = {
              "Subject": "Discuss the Calendar REST API",
              "Body": {
                "ContentType": "HTML",
                "Content": "I think it will meet our requirements!"
              },
              "Start": {
                  "DateTime": "2014-04-04T18:00:00",
                  "TimeZone": "Pacific Standard Time"
              },
              "End": {
                  "DateTime": "2014-04-04T19:00:00",
                  "TimeZone": "Pacific Standard Time"
              },
              "Attendees": [
                {
                  "EmailAddress": {
                    "Address": "[email protected]",
                    "Name": "Janet Schorr"
                  },
                  "Type": "Required"
                }
              ]
            }

    if (method.upper() == 'GET'):
        response = requests.get(url, headers = headers, params = parameters)
    elif (method.upper() == 'DELETE'):
        response = requests.delete(url, headers = headers, params = parameters)
    elif (method.upper() == 'PATCH'):
        headers.update({ 'Content-Type' : 'application/json' })
        response = requests.patch(url, headers = headers, data = json.dumps(payload), params = parameters)
    elif (method.upper() == 'POST'):
        headers.update({ 'Content-Type' : 'application/json' })
        response = requests.post(url, headers = headers, data = json.dumps(payload), params = parameters)

    return response 
Example 77
Project: LMS   Author: RRZE-HPC   File: api.py    GNU General Public License v3.0 4 votes vote down vote up
def __request_requests(self, url, method, data=None):
        out = self.empty_json
        if isinstance(data, dict):
            data = json.dumps(data)
        elif data:
            try:
                data = json.loads(data)
            except ValueError:
                print "Input not a valid JSON document"
                return 400, "Input not a valid JSON document", out
        try:
            if method == 'GET':
                return _get_requests(url, headers=self.headers,
                                     auth=(self.username, self.password),
                                     timeout=self.timeout)
            elif method == 'PUSH':
                return _post_requests(url, data=data, headers=self.headers,
                                      auth=(self.username, self.password),
                                      timeout=self.timeout)
            elif method == 'DELETE':
                r = requests.delete(url, headers=self.headers,
                                    auth=(self.username, self.password),
                                    timeout=self.timeout)
            elif method == 'PUT':
                r = requests.put(url, data=data, headers=self.headers,
                                 auth=(self.username, self.password),
                                 timeout=self.timeout)
            elif method == 'PATCH':
                r = requests.patch(url, data=data, headers=self.headers,
                                   auth=(self.username, self.password),
                                   timeout=self.timeout)
        except requests.Timeout as e:
            print "Timeout for URL %s: %s" % (url,e,)
            print "Headers: %s" % (str(self.headers),)
            return 400, "Timeout for url %s: %s" % (url,e,), out
        except requests.ProxyError as e:
            print "ProxyError for URL %s: %s" % (url,e,)
            print "Headers: %s" % (str(self.headers),)
            return 400, "ProxyError for url %s: %s" % (url,e,), out
        except requests.SSLError as e:
            print "SSLError for URL %s: %s" % (url,e,)
            print "Headers: %s" % (str(self.headers),)
            return 400, "SSLError for url %s: %s" % (url,e,), out
        except requests.ConnectionError as e:
            print "ConnectionError for URL %s: %s" % (url,e,)
            print "Headers: %s" % (str(self.headers),)
            return 400, "ConnectionError for url %s: %s" % (url,e,), out
        except requests.HTTPError as e:
            print "HTTPError for URL %s: %s" % (url,e,)
            print "Headers: %s" % (str(self.headers),)
            return 400, "HTTPError for url %s: %s" % (url,e,), out
        except requests.RequestException as e:
            print "RequestException for URL %s: %s" % (url,e,)
            print "Headers: %s" % (str(self.headers),)
            return 400, "RequestException for url %s: %s" % (url,e,), out
        return r.status_code, "OK", r.json() 
Example 78
Project: azure-apim-deployment-utils   Author: Haufe-Lexware   File: apim_core.py    Apache License 2.0 4 votes vote down vote up
def update_swagger(self, instance, swaggerfiles):
        sas_token = self._token_factory.get_sas_token(instance)
        base_url = self._token_factory.get_base_url(instance)
        api_version = self._token_factory.get_api_version()
        # First, find the ids of the APIs.
        api_res = requests.get(base_url + 'apis' + api_version,
                               headers = {'Authorization': sas_token})
        if (200 != api_res.status_code):
            print "Could not retrieve API information (/api endpoint)."
            print api_res.text
            return False

        apis_json = byteify(json.loads(api_res.text))

        api_id_bag = {}
        api_bag = {}
        for api_def in apis_json['value']:
            api_url = api_def['serviceUrl']
            api_id_url = api_def['id'] # /apis/3498734a389f7bc83749837493
            api_id = api_id_url[api_id_url.index('/', 2) + 1:]
            api_name = api_def['name']
            print "Found API '" + api_name + "' (id " + api_id + ")."
            api_id_bag[api_url] = api_id
            api_bag[api_url] = api_def

        for swaggerfile in swaggerfiles['swaggerFiles']:
            print "Updating '" + swaggerfile['swagger'] + "'."
            swagger_url = swaggerfile['serviceUrl']
            if swagger_url not in api_id_bag:
                print "Could not find serviceUrl '" + swagger_url + "'. Is it a new API? Import it once first in the Web UI."
                return False
            
            api_id = api_id_bag[swagger_url]
            swagger_json = self.__load_swagger(instance, swaggerfile['swagger'])
            swag_res = requests.put(base_url + 'apis/' + api_id + api_version + '&import=true',
                                    headers={'Authorization': sas_token,
                                             'If-Match': '*',
                                             'Content-Type': 'application/vnd.swagger.doc+json'},
                                    json = swagger_json)
            if (204 != swag_res.status_code):
                print "Updating the API did not succeed."
                print swag_res.status_code
                return False
            # Re-update the API definition because the Swagger import overwrites the serviceUrl
            api_res = requests.patch(base_url + 'apis/' + api_id + api_version,
                                     headers = {'Authorization': sas_token,
                                                'If-Match': '*'},
                                     json = api_bag[swagger_url])
            if (204 != api_res.status_code):
                print "Could not update serviceUrl (next update will break!)."
                print api_res.text
                return False
            print "Update succeeded."

        return True 
Example 79
Project: IxNetwork   Author: OpenIxia   File: ResumeRestConfig.py    MIT License 4 votes vote down vote up
def enableDisableBgpFlapNgpf(sessionUrl, action='true', upTimeInSec=0, downTimeInSec=0):
    # This API will enable or disable flapping on all the BGP interfaces.
    #
    # sessionUrl = The BGP object handle.
    #              http://10.219.117.x:11009/api/v1/sessions/1/ixnetwork/topology/1/deviceGroup/1/ethernet/1/ipv4/1/bgpIpv4Peer/1
    # 
    # action     = string format.  Not boolean.
    #              'true'  = enable BGP flap.
    #              'false' = disable BGP flap.
    #
    # upTimeInSecs   = Up Time In Seconds.  Provide an integer.
    # downTimeInSecs = Down Time In Seconds. Provide an integer.

    urlHeadersJson = {'content-type': 'application/json'}
    httpHeader = sessionUrl.split('/api')[0]
    print '\nenableBgpRouteFlapNgpf: Please wait a moment while I query for datas...'
    response = requests.get(sessionUrl)
    if response.status_code != 200:
        return 1

    # NOTE:  This will take a moment if the config is large
    # /api/v1/sessions/1/ixnetwork/multivalue/600
    flapMultivalue = response.json()['flap']

    upTimeInSecsMultivalue = response.json()['uptimeInSec']
    downTimeInSecsMultivalue = response.json()['downtimeInSec']

    print '\nenableDisableBgpFlapNgpf:', action
    response = requests.patch(httpHeader+flapMultivalue+'/singleValue',
                              data=json.dumps({'value': action}),
                              headers=urlHeadersJson)
    if response.status_code != 200:
        return 1

    print 'enableDisableBgpFlapNgpf upTimeInSec:', upTimeInSec
    response = requests.patch(httpHeader+upTimeInSecsMultivalue+'/singleValue',
                              data=json.dumps({'value': str(upTimeInSec)}),
                              headers=urlHeadersJson)
    if response.status_code != 200:
        return 1

    print 'enableDisableBgpFlapNgpf downTimeInSec:', downTimeInSec
    response = requests.patch(httpHeader+downTimeInSecsMultivalue+'/singleValue',
                              data=json.dumps({'value': str(downTimeInSec)}),
                              headers=urlHeadersJson)
    if response.status_code != 200:
        return 1 
Example 80
Project: IxNetwork   Author: OpenIxia   File: ixVmChassisBuilderRestApi.py    MIT License 4 votes vote down vote up
def ixVmConfigCardId(self, cardName=None, mgmtIp='', keepAlive=300):
        """
        Description
           Add/Configure a virtual line card.

        Syntax
           http://{apiServerIp:11009}/availableHardware/virtualChassis/ixVmCard

        Parameters
           cardId:   The cardId.  Must begin with 1 and in sequential order.
           cardName: Optional: Specify a name for the card.
           mgmtIp:   The virtual line card's management IP address.
           keepAlive: Integer in seconds
        """
        url = self.sessionUrl+'/availableHardware/virtualChassis/ixVmCard'
        nextCardId = self.ixVmGetLastCardId()+1
        data = {"cardId": str(nextCardId),
                "managementIp": str(mgmtIp),
                "keepAliveTimeout": int(keepAlive)
                }
        response = self.post(url, data=data, ignoreError=True)
        if response.status_code == 400:
            print()
            # Another card with IP 192.168.70.130 already exists on slot 1 on the chassis 192.168.70.10.
            # Commit operation failed on /availableHardware/virtualChassis/ixVmCard:L100
            for error in response.json()['errors']:
                print('\t', error['detail'])

            print('\nREMOVING existing cardID:', mgmtIp)
            self.ixVmRemoveCardId(mgmtIp)

            print('\nRETRY creating cardID:', mgmtIp)
            response = self.patch(url, data=data)
            if response.status_code == 400:
                print()
                # Another card with IP 192.168.70.130 already exists on slot 1 on the chassis 192.168.70.10.
                # Commit operation failed on /availableHardware/virtualChassis/ixVmCard:L100
                for error in response.json()['errors']:
                    print('\t', error['detail'])

            #raise IxNetRestApiException
        
        if cardName is not None:
            self.patch(url, data={'cardName': cardName})

        ixVmCardObj = response.json()['links'][0]['href']
        return ixVmCardObj