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: 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 #2
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 #3
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 #4
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 #5
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 #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.projectdb.drop_database() 
Example #7
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 #8
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 #9
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 #10
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 #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 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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #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: 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 #22
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 #23
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 #24
Source File: _BaseClient.py    From docker-registry-client with Apache License 2.0 5 votes vote down vote up
def delete_repository(self, namespace, repository):
        """DELETE /v1/repositories/(namespace)/(repository)/"""
        return self._http_call(self.REPO, delete,
                               namespace=namespace, repository=repository) 
Example #25
Source File: client.py    From GitterPy with MIT License 5 votes vote down vote up
def delete(self, api, **kwargs):
        return self.request_process(r.delete, api, **kwargs) 
Example #26
Source File: client.py    From GitterPy with MIT License 5 votes vote down vote up
def leave(self, room_name):
        room_id = self.get_room(room_name)
        user_id = self.get_user_id
        api_meth = 'rooms/{}/users/{}'.format(room_id, user_id)
        return self.delete(api_meth) 
Example #27
Source File: client.py    From GitterPy with MIT License 5 votes vote down vote up
def delete_room(self, room_name):
        api_meth = 'rooms/{}'.format(self.get_room(room_name))
        return self.delete(api_meth) 
Example #28
Source File: app.py    From controller with 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 #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)