Python requests.delete() Examples

The following are 30 code examples for showing how to use requests.delete(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module requests , or try the search function .

Example 1
Project: controller   Author: deis   File: app.py    License: MIT License 6 votes vote down vote up
def autoscale(self, proc_type, autoscale):
        """
        Set autoscale rules for the application
        """
        name = '{}-{}'.format(self.id, proc_type)
        # basically fake out a Deployment object (only thing we use) to assign to the HPA
        target = {'kind': 'Deployment', 'metadata': {'name': name}}

        try:
            # get the target for autoscaler, in this case Deployment
            self._scheduler.hpa.get(self.id, name)
            if autoscale is None:
                self._scheduler.hpa.delete(self.id, name)
            else:
                self._scheduler.hpa.update(
                    self.id, name, proc_type, target, **autoscale
                )
        except KubeHTTPException as e:
            if e.response.status_code == 404:
                self._scheduler.hpa.create(
                    self.id, name, proc_type, target, **autoscale
                )
            else:
                # let the user know about any other errors
                raise ServiceUnavailable(str(e)) from e 
Example 2
Project: unicorn-binance-websocket-api   Author: oliver-zehentleitner   File: unicorn_binance_websocket_api_restclient.py    License: MIT License 6 votes vote down vote up
def delete_listen_key(self, listen_key):
        """
        Delete a specific listen key

        :param listen_key: the listenkey you want to delete
        :type listen_key: str

        :return: the response
        :rtype: str or False
        """
        logging.debug("BinanceWebSocketApiRestclient->delete_listen_key(" + str(listen_key) + ")")
        method = "delete"
        try:
            return self._request(method, self.path_userdata, False, {'listenKey': str(listen_key)})
        except KeyError:
            return False
        except TypeError:
            return False 
Example 3
Project: python-wp   Author: myles   File: api.py    License: MIT License 6 votes vote down vote up
def delete_post(self, pk, force=False):
        """
        Delete a Post.

        Arguments
        ---------

        pk : int
            The post id you want to delete.
        force : bool
            Whether to bypass trash and force deletion.
        """
        resp = self._delete('posts/{0}'.format(pk), params=locals())

        if resp.status_code == 200:
            return True
        else:
            raise Exception(resp.json())

    # Post Reivion Methods 
Example 4
Project: certidude   Author: laurivosandi   File: authority.py    License: MIT License 6 votes vote down vote up
def delete_request(common_name, user="root"):
    # Validate CN
    if not re.match(const.RE_COMMON_NAME, common_name):
        raise ValueError("Invalid common name")

    path, buf, csr, submitted = get_request(common_name)
    os.unlink(path)

    logger.info("Rejected signing request %s by %s" % (
        common_name, user))

    # Publish event at CA channel
    push.publish("request-deleted", common_name)

    # Write empty certificate to long-polling URL
    requests.delete(
        config.LONG_POLL_PUBLISH % hashlib.sha256(buf).hexdigest(),
        headers={"User-Agent": "Certidude API"}) 
Example 5
Project: pyspider   Author: binux   File: test_run.py    License: Apache License 2.0 6 votes vote down vote up
def test_50_docker_rabbitmq(self):
        try:
            os.environ['RABBITMQ_NAME'] = 'rabbitmq'
            os.environ['RABBITMQ_PORT_5672_TCP_ADDR'] = 'localhost'
            os.environ['RABBITMQ_PORT_5672_TCP_PORT'] = '5672'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            queue = ctx.obj.newtask_queue
            queue.put('abc')
            queue.delete()
        except Exception as e:
            self.assertIsNone(e)
        finally:
            del os.environ['RABBITMQ_NAME']
            del os.environ['RABBITMQ_PORT_5672_TCP_ADDR']
            del os.environ['RABBITMQ_PORT_5672_TCP_PORT'] 
Example 6
Project: single_cell_portal   Author: broadinstitute   File: scp_api.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_delete(self, command, dry_run=False):
        '''
        Perform Delete

        :param command: String DELETE command to send to the REST endpoint
        :param dry_run: If true, will do a dry run with no actual execution of functionality.
        :return: Dict with response and status code/status
        '''

        ## TODO add timeout and exception handling (Timeout exeception)
        if self.verbose:
            print("DO DELETE")
            print(command)
        if dry_run:
            return({c_SUCCESS_RET_KEY: True,c_CODE_RET_KEY: c_DELETE_OK})
        head = {c_AUTH: 'token {}'.format(self.token), 'Accept': 'application/json'}
        return(self.check_api_return(requests.delete(command, headers=head, verify=self.verify_https))) 
Example 7
Project: single_cell_portal   Author: broadinstitute   File: scp_api.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete_study_external_resource(self, study_name,
                                       resource_id,
                                       dry_run=False):
        '''
        Delete a study's external resource using the REST API.

        :param study_name: String study name
        :param resource_ids: String Id of external resource to delete
        :param dry_run: If true, will do a dry run with no actual execution of functionality.
        :return: Response
        '''
        if self.verbose: print("LOOKING AT " + study_name)
        # Error if the study does not exist
        if not self.study_exists(study_name=study_name, dry_run=dry_run) and not dry_run:
            return {
                c_SUCCESS_RET_KEY: False,
                c_CODE_RET_KEY: c_STUDY_DOES_NOT_EXIST
            }
        # Convert study name to study id
        study_id = self.study_name_to_id(study_name, dry_run=dry_run)
        ret_delete = self.do_delete(command=self.api_base + "studies/"+str(study_id) +
                                    "/external_resources/" + resource_id,
                                    dry_run=dry_run)

        return(ret_delete) 
Example 8
Project: tinycards-python-api   Author: floscha   File: rest_api.py    License: MIT License 6 votes vote down vote up
def unsubscribe(self, user_id):
        """Unsubscribe the given user.

        Args:
            user_id: ID of the user to unsubscribe.

        Returns: If successful, returns the ID of the unsubscribed user.

        """
        request_url = API_URL + 'users/' + str(user_id) + '/subscriptions'
        r = requests.delete(url=request_url, cookies={'jwt_token': self.jwt})

        json_response = r.json()
        removed_subscription = json_response['removedSubscription']

        return removed_subscription

    # --- Deck CRUD 
Example 9
Project: tinycards-python-api   Author: floscha   File: rest_api.py    License: MIT License 6 votes vote down vote up
def delete_deck(self, deck_id):
        """Delete an existing deck.

        Args:
            deck_id (str): The ID of the Deck to delete.

        Returns:
            Deck: The deleted Deck object if deletion was successful.

        """
        if not isinstance(deck_id, str):
            raise ValueError("'deck_id' parameter must be of type str")

        headers = DEFAULT_HEADERS

        r = requests.delete(url=API_URL + 'decks/' + deck_id, headers=headers,
                            cookies={'jwt_token': self.jwt})

        json_data = r.json()
        deleted_deck = json_converter.json_to_deck(json_data)

        return deleted_deck

    # --- Favorites CR(U)D 
Example 10
Project: tinycards-python-api   Author: floscha   File: rest_api.py    License: MIT License 6 votes vote down vote up
def remove_favorite(self, user_id, favorite_id):
        """Add a deck to the current user's favorites.

        Args:
            user_id (int): ID of the user to favorite the deck for.
            favorite_id (str): The ID of the favorite to be removed.

        Returns:
            str: The ID of the removed favorite.

        """
        request_url = API_URL + 'users/%d/favorites/%s' % (user_id,
                                                           favorite_id)
        r = requests.delete(url=request_url, cookies={'jwt_token': self.jwt})

        json_response = r.json()
        removed_favorite_id = json_response['removedFavoriteId']

        return removed_favorite_id

    # --- Search 
Example 11
Project: alice_blue   Author: krishnavelu   File: alice_blue.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __api_call(self, url, http_method, data):
        #logger.debug('url:: %s http_method:: %s data:: %s headers:: %s', url, http_method, data, headers)
        headers = {"Content-Type": "application/json"} 
        if(len(self.__access_token) > 100):
            headers['X-Authorization-Token'] = self.__access_token
            headers['Connection'] = 'keep-alive'
        else:
            headers['client_id'] = self.__username
            headers['authorization'] = f"Bearer {self.__access_token}"
        r = None
        if http_method is Requests.POST:
            r = requests.post(url, data=json.dumps(data), headers=headers)
        elif http_method is Requests.DELETE:
            r = requests.delete(url, headers=headers)
        elif http_method is Requests.PUT:
            r = requests.put(url, data=json.dumps(data), headers=headers)
        elif http_method is Requests.GET:
            r = requests.get(url, headers=headers)
        return r 
Example 12
Project: salt-cloudflare   Author: cloudflare   File: cloudflare.py    License: MIT License 6 votes vote down vote up
def _request(self, uri, method="GET", json=None):
        if self.api_token:
            headers = {"Authorization": "Bearer {0}".format(self.api_token)}
        else:
            headers = {"X-Auth-Email": self.auth_email, "X-Auth-Key": self.auth_key}

        logger.info("Sending request: {0} {1} data: {2}".format(method, uri, json))

        if method == "GET":
            resp = requests.get(uri, headers=headers)
        elif method == "POST":
            resp = requests.post(uri, headers=headers, json=json)
        elif method == "PUT":
            resp = requests.put(uri, headers=headers, json=json)
        elif method == "DELETE":
            resp = requests.delete(uri, headers=headers)
        else:
            raise Exception("Unknown request method: {0}".format(method))

        if not resp.ok:
            raise Exception(
                "Got HTTP code {0}: {1}".format(resp.status_code, resp.text)
            )

        return resp.json() 
Example 13
Project: blocktrail-sdk-python   Author: blocktrail   File: connection.py    License: MIT License 6 votes vote down vote up
def delete(self, endpoint_url, data=None, params=None, auth=None):
        """
        :param str      endpoint_url:   the API endpoint to request
        :param dict     data:           the POST body
        :param bool     auth:           do HMAC auth
        :rtype: requests.Response
        """
        if auth is True:
            auth = self.auth

        data = json.dumps(data)

        params = dict_merge(self.default_params, params)

        headers = dict_merge(self.default_headers, {
            'Date': RestClient.httpdate(datetime.datetime.utcnow()),
            'Content-MD5': RestClient.content_md5(urlparse(self.api_endpoint + endpoint_url).path + "?" + urlencode(params)),
            'Content-Type': 'application/json'
        })

        response = requests.delete(self.api_endpoint + endpoint_url, data=data, params=params, headers=headers, auth=auth)

        return self.handle_response(response) 
Example 14
Project: LuckyCAT   Author: fkie-cad   File: fuzzjob_manager.py    License: GNU General Public License v3.0 6 votes vote down vote up
def delete_job(args):
    if args.name is None:
        logger.error("Please provide a valid name of a job.")
    else:

        if not query_yes_no("Do you want to delete the job %s?" % args.name):
            logger.error("Aborting...")
            sys.exit(1)

        job_id = find_job_id_by_name(args)
        if job_id:
            url = urljoin(args.url, "/api/job/%s" % job_id)
            response = requests.delete(url, headers={'Authorization': args.token,
                                                     'content-type': 'application/json'},
                                       verify=args.ssl_verify)
            if response.status_code != 200:
                logging.error("Could not delete job %s: %s" % (args.name, response.text))
            else:
                logging.info("Deleted job %s." % args.name)
        else:
            logging.error("Could not find job %s." % args.name) 
Example 15
Project: workload-collocation-agent   Author: intel   File: kubeapi.py    License: Apache License 2.0 6 votes vote down vote up
def delete(self, target):
        full_url = urljoin(
                self.endpoint,
                target)

        r = requests.delete(
                full_url,
                headers={
                    "Authorization": "Bearer {}".format(self.service_token),
                    },
                timeout=self.timeout,
                verify=self.server_cert_ca_path)

        if not r.ok:
            log.error('An unexpected error occurred for target "%s": %i %s - %s',
                      target, r.status_code, r.reason, r.raw)
        r.raise_for_status()

        return r.json() 
Example 16
Project: SalesforcePy   Author: forcedotcom   File: sfdc.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(self, **kwargs):
        """ Deletes an SObject in Salesforce.

          :return: Delete result from Salesforce
          :rtype: (None, SObject)
        """

        _client = self.__client__
        resource_id = self.get_service()
        k = {
            'http_method': 'DELETE',
            'resource_id': resource_id
        }
        k.update(kwargs)
        sobj = SObjects(_client, **k)
        req = sobj.request()
        return req, sobj 
Example 17
Project: insightconnect-plugins   Author: rapid7   File: action.py    License: MIT License 6 votes vote down vote up
def run(self, params={}):
        url = requests.compat.urljoin(self.connection.api_prefix, '/user/blocks/' + urllib.parse.quote(params.get('username')))
        headers = {
            'Accept': 'application/vnd.github.giant-sentry-fist-preview+json',
            'Content-Type': 'application/json',
        }

        response = requests.delete(url, headers=headers, auth=(self.connection.username, self.connection.secret))

        try:
            data = response.json()
        except ValueError:
            if response.status_code == 204:
                self.logger.info('Successfully unblocked user')
                return { 'success': True }

        return { 'success': False } 
Example 18
Project: insightconnect-plugins   Author: rapid7   File: action.py    License: MIT License 6 votes vote down vote up
def run(self, params={}):
        user_principal_name = params.get(Input.USER_PRINCIPAL_NAME)
        token = self.connection.access_token

        base_url = 'https://graph.microsoft.com/beta/users/%s' % user_principal_name
        headers = {'Authorization': 'Bearer %s' % token}

        try:
            response = requests.delete(base_url, headers=headers)
        except requests.HTTPError:
            raise PluginException(cause=f"There was an issue with the Delete User request. Double-check the username: {user_principal_name}",
                                  data=response.text)
        if response.status_code == 204:
            success = True
            return {Output.SUCCESS: success}
        else:
            raise PluginException(cause="The response from Office365 indicated something went wrong: {response.status_code}",
                                  data=response.text) 
Example 19
Project: gitfollow   Author: sepandhaghighi   File: gitfollow.py    License: MIT License 6 votes vote down vote up
def unfollow(username,password,id_list):
    for user in id_list:
        response=requests.delete("https://api.github.com/user/following/" + user, auth=(username, password))
        status_code=int(response.status_code)
        if status_code!=204:
            if status_code==401:
                print("[Error] Authentication Error")
                return False
            elif status_code==403:
                print("[Error] Maximum number of login attempts exceeded")
                sys.exit()
            else:
                print("[Error] in " + user + " unfollow!")
        else:
            print(user+" Unfollowed")
        time.sleep(3)
    return True 
Example 20
Project: BASS   Author: Cisco-Talos   File: client.py    License: GNU General Public License v2.0 5 votes vote down vote up
def delete(self):
        reply = requests.delete("%s/job/%d" % (self.url, self.id))
        if reply.status_code != 200:
            try:
                message = reply.json()["message"]
            except ValueError:
                message = reply.content
            raise RuntimeError("Server returned error code %d: %s" % (reply.status_code, message)) 
Example 21
Project: hubic-wrapper-to-swift   Author: puzzle1536   File: hubic.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delete(self, hubic_api):

        hubic_api_url = 'https://api.hubic.com/1.0%s' % hubic_api

        if self.access_token:

            if options.verbose:
                print "-- DELETE request to hubic API : %s" % hubic_api

            if self.token_expire <= time():
                print "-- Access token has expired, trying to renew it"
                self.refresh()

            bearer_auth = HTTPBearerAuth(self.access_token)
            r = requests.delete(hubic_api_url, auth=bearer_auth)

            try:
                # Check if token is still valid
                if r.status_code == 401 and r.json()['error'] == 'invalid_token' and r.json()['error_description'] == 'expired':
                    # Try to renew if possible
                    print "-- Access token has expired, trying to renew it"
                    self.refresh()
                    r = requests.post(hubic_api_url, auth=bearer_auth)

                if r.status_code == 404 or r.status_code == 500:
                    print "%s : %s" % (r.json()['code'], r.json()['message'])
                    return

                if r.status_code != 200:
                    print "%s : %s" % (r.json()['error'], r.json()['error_description'])
                    return

            except:
                print "Something wrong has happened when accessing hubic API (DELETE request)"
                sys.exit(10)

            for keys in r.json():
                print "%s : %s" % (keys,r.json()[keys]) 
Example 22
Project: marketo-rest-python   Author: jepcastelein   File: http_lib.py    License: MIT License 5 votes vote down vote up
def delete(self, endpoint, args, data):
        headers = {'Content-type': 'application/json; charset=utf-8'}
        r = requests.delete(endpoint, params=args, json=data, headers=headers)
        r_json = r.json()
        if r_json.get('success'):
            return r.json()
        else:
            raise MarketoException(r_json['errors'][0]) 
Example 23
Project: CyberTK-Self   Author: CyberTKR   File: channel.py    License: GNU General Public License v2.0 5 votes vote down vote up
def deleteAlbum(self,gid,albumId):
        header = {
            "Content-Type" : "application/json",
            "X-Line-Mid" : self.mid,
            "x-lct": self.channel_access_token,

        }
        r = requests.delete(
            "http://" + self.host + "/mh/album/v3/album/" + albumId + "?homeId=" + gid,
            headers = header,
            )
        return r.json() 
Example 24
Project: python-rest-api   Author: messagebird   File: http_client.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def request(self, path, method='GET', params=None, format=ResponseFormat.text):
        """Builds a request and gets a response."""
        if params is None:
            params = {}
        url = urljoin(self.endpoint, path)
        headers = {
            'Accept': 'application/json',
            'Authorization': 'AccessKey ' + self.access_key,
            'User-Agent': self.user_agent,
            'Content-Type': 'application/json'
        }

        method_switcher = {
            'DELETE': lambda: requests.delete(url, verify=True, headers=headers, data=json_serialize(params)),
            'GET': lambda: requests.get(url, verify=True, headers=headers, params=params),
            'PATCH': lambda: requests.patch(url, verify=True, headers=headers, data=json_serialize(params)),
            'POST': lambda: requests.post(url, verify=True, headers=headers, data=json_serialize(params)),
            'PUT': lambda: requests.put(url, verify=True, headers=headers, data=json_serialize(params))
        }
        if method not in method_switcher:
            raise ValueError(str(method) + ' is not a supported HTTP method')

        response = method_switcher[method]()

        if response.status_code not in self.__supported_status_codes:
            response.raise_for_status()

        response_switcher = {
            ResponseFormat.text: response.text,
            ResponseFormat.binary: response.content
        }
        return response_switcher.get(format) 
Example 25
Project: pyfirebase   Author: afropolymath   File: firebase.py    License: MIT License 5 votes vote down vote up
def delete(self):
        return requests.delete(self.current_url) 
Example 26
Project: controller   Author: deis   File: app.py    License: MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        """Delete this application including all containers"""
        self.log("deleting environment")
        try:
            # check if namespace exists
            self._scheduler.ns.get(self.id)

            try:
                self._scheduler.ns.delete(self.id)

                # wait 30 seconds for termination
                for _ in range(30):
                    try:
                        self._scheduler.ns.get(self.id)
                    except KubeHTTPException as e:
                        # only break out on a 404
                        if e.response.status_code == 404:
                            break
            except KubeException as e:
                raise ServiceUnavailable('Could not delete Kubernetes Namespace {} within 30 seconds'.format(self.id)) from e  # noqa
        except KubeHTTPException:
            # it's fine if the namespace does not exist - delete app from the DB
            pass

        self._clean_app_logs()
        return super(App, self).delete(*args, **kwargs) 
Example 27
Project: controller   Author: deis   File: app.py    License: MIT License 5 votes vote down vote up
def _clean_app_logs(self):
        """Delete application logs stored by the logger component"""
        try:
            url = 'http://{}:{}/logs/{}'.format(settings.LOGGER_HOST,
                                                settings.LOGGER_PORT, self.id)
            requests.delete(url)
        except Exception as e:
            # Ignore errors deleting application logs.  An error here should not interfere with
            # the overall success of deleting an application, but we should log it.
            err = 'Error deleting existing application logs: {}'.format(e)
            self.log(err, logging.WARNING) 
Example 28
Project: controller   Author: deis   File: app.py    License: MIT License 5 votes vote down vote up
def _update_application_service(self, namespace, app_type, port, routable=False, annotations={}):  # noqa
        """Update application service with all the various required information"""
        service = self._fetch_service_config(namespace)
        old_service = service.copy()  # in case anything fails for rollback

        try:
            # Update service information
            for key, value in annotations.items():
                if value is not None:
                    service['metadata']['annotations']['router.deis.io/%s' % key] = str(value)
                else:
                    service['metadata']['annotations'].pop('router.deis.io/%s' % key, None)
            if routable:
                service['metadata']['labels']['router.deis.io/routable'] = 'true'
            else:
                # delete the annotation
                service['metadata']['labels'].pop('router.deis.io/routable', None)

            # Set app type selector
            service['spec']['selector']['type'] = app_type

            # Find if target port exists already, update / create as required
            if routable:
                for pos, item in enumerate(service['spec']['ports']):
                    if item['port'] == 80 and port != item['targetPort']:
                        # port 80 is the only one we care about right now
                        service['spec']['ports'][pos]['targetPort'] = int(port)

            self._scheduler.svc.update(namespace, namespace, data=service)
        except Exception as e:
            # Fix service to old port and app type
            self._scheduler.svc.update(namespace, namespace, data=old_service)
            raise ServiceUnavailable(str(e)) from e 
Example 29
Project: python-wp   Author: myles   File: api.py    License: MIT License 5 votes vote down vote up
def _delete(self, endpoint, params={}):
        """
        Private function for making DELETE requests.

        Arguments
        ---------

        endpoint : str
            WordPress endpoint.
        params : dict
            HTTP parameters when making the connection.

        Returns
        -------

        dict/list
            Returns the data from the endpoint.
        """
        url = urljoin(self.url, 'wp', self.version, endpoint)

        resp = requests.delete(url, params=params, headers=self.headers)

        if not resp.status_code == 200:
            msg = ('WordPress REST API returned the status code '
                   '{0}.'.foramt(resp.status_code))
            raise Exception(msg)

        return resp.json()

    # Post Methods 
Example 30
Project: operator-courier   Author: operator-framework   File: test_push.py    License: Apache License 2.0 5 votes vote down vote up
def ensure_application_release_removed(repository_name, release_version):
    api = f'https://quay.io/cnr/api/v1/packages/' \
          f'{quay_namespace}/{repository_name}/{release_version}/helm'
    headers = {
        'Content-Type': 'application/json',
        'Authorization': quay_access_token
    }
    res = requests.delete(api, headers=headers)
    assert res.status_code == 200