Python requests.delete() Examples

The following are 30 code examples of requests.delete(). 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 also want to check out all available functions/classes of the module requests , or try the search function .
Example #1
Source File: app.py    From controller with 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
Source File: unicorn_binance_websocket_api_restclient.py    From unicorn-binance-websocket-api with 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
Source File: api.py    From python-wp with 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
Source File: authority.py    From certidude with 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
Source File: test_database.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def tearDownClass(self):
        # remove the test admin user
        import requests
        from requests.auth import HTTPBasicAuth
        requests.delete('http://localhost:5984/_node/_local/_config/admins/test',
                        auth=HTTPBasicAuth('test', 'password'))
        del os.environ["COUCHDB_USER"]
        del os.environ["COUCHDB_PASSWORD"]
        self.projectdb.drop_database() 
Example #6
Source File: test_database.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def tearDownClass(self):
        # remove the test admin user
        import requests
        from requests.auth import HTTPBasicAuth
        requests.delete('http://localhost:5984/_node/_local/_config/admins/test',
                        auth=HTTPBasicAuth('test', 'password'))
        del os.environ["COUCHDB_USER"]
        del os.environ["COUCHDB_PASSWORD"]
        self.resultdb.drop_database() 
Example #7
Source File: test_run.py    From pyspider with 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 #8
Source File: test_run.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def test_60a_docker_couchdb(self):
        try:
            # create a test admin user
            import requests
            requests.put('http://localhost:5984/_node/_local/_config/admins/test',
                         data='"password"')
            os.environ['COUCHDB_NAME'] = 'couchdb'
            os.environ['COUCHDB_PORT_5984_TCP_ADDR'] = 'localhost'
            os.environ['COUCHDB_PORT_5984_TCP_PORT'] = '5984'
            os.environ["COUCHDB_USER"] = "test"
            os.environ["COUCHDB_PASSWORD"] = "password"
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            ctx.obj.resultdb
        except Exception as e:
            self.assertIsNone(e)
        finally:
            # remove the test admin user
            import requests
            from requests.auth import HTTPBasicAuth
            requests.delete('http://localhost:5984/_node/_local/_config/admins/test',
                            auth=HTTPBasicAuth('test', 'password'))
            del os.environ['COUCHDB_NAME']
            del os.environ['COUCHDB_PORT_5984_TCP_ADDR']
            del os.environ['COUCHDB_PORT_5984_TCP_PORT']
            del os.environ["COUCHDB_USER"]
            del os.environ["COUCHDB_PASSWORD"] 
Example #9
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def delete(self, url):
        return requests.delete(url,
                               headers={"Content-Type": "application/json"},
                               auth=HTTPBasicAuth(self.username, self.password)).json() 
Example #10
Source File: scp_api.py    From single_cell_portal with 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 #11
Source File: scp_api.py    From single_cell_portal with 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 #12
Source File: rest_api.py    From tinycards-python-api with 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 #13
Source File: rest_api.py    From tinycards-python-api with 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 #14
Source File: rest_api.py    From tinycards-python-api with 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 #15
Source File: alice_blue.py    From alice_blue with 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 #16
Source File: cloudflare.py    From salt-cloudflare with 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 #17
Source File: connection.py    From blocktrail-sdk-python with 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 #18
Source File: fuzzjob_manager.py    From LuckyCAT with 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 #19
Source File: kubeapi.py    From workload-collocation-agent with 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 #20
Source File: sfdc.py    From SalesforcePy with 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 #21
Source File: action.py    From insightconnect-plugins with 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 #22
Source File: action.py    From insightconnect-plugins with 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 #23
Source File: gitfollow.py    From gitfollow with 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 #24
Source File: client.py    From BASS with 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 #25
Source File: hubic.py    From hubic-wrapper-to-swift with 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 #26
Source File: http_lib.py    From marketo-rest-python with 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 #27
Source File: channel.py    From CyberTK-Self with 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 #28
Source File: http_client.py    From python-rest-api with 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 #29
Source File: firebase.py    From pyfirebase with MIT License 5 votes vote down vote up
def delete(self):
        return requests.delete(self.current_url) 
Example #30
Source File: app.py    From controller with 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)