Esempio n. 1
0
def delete():
    '''
    Delete images
    '''

    # if img['dmca'] == 1 or img['illegal'] == 1:
    #     print board + '/' +  img['threadID'] + "/" + img['local_thumbnail']
    #     query = '''UPDATE {0}_mod SET imgur_thumbnail_url = 'test' WHERE local_thumbnail = %s'''.format(board)
    #     engine.execute(query, img['local_thumbnail'])

    # to_delete = ["692LfMR1HKotuic","nbxl2ZAcOTO2eoz", "nrsNcrYqUV0A9rH"]
    to_delete = engine.execute("SELECT * FROM sci_mod")

    # for row in to_delete:
    #     if row['dmca'] == 1 or row['illegal'] == 1:
    #         print "something"


    for row in to_delete:
        if (row['dmca'] == 1 or row['illegal'] == 1) and (row['imgur_thumbnail_url'] is not None or row['imgur_image_url'] is not None):
        # client.delete_image(img)
        # # These code snippets use an open-source library.
        # These code snippets use an open-source library. http://unirest.io/python
            response = unirest.delete("https://imgur-apiv3.p.mashape.com/3/image/{}".format(row['imgur_deletehash']),
                                      headers={
                                          "X-Mashape-Key": "y4mVnnNiZBmshBb9s7rh4DSw6K53p1T5SDujsnxxEUEvw62m4L",
                                          "Authorization": "Client-ID 999ee789e084f2e",
                                          "Accept": "text/plain"
                                      }
                                      )
            print response.body['status']

            if response.body['status'] == 200:
                print "was successful"
Esempio n. 2
0
def delete():
    '''
    Delete images
    '''


    to_delete = engine.execute("SELECT * FROM sci_mod")




    for row in to_delete:
        if (row['dmca'] == 1 or row['illegal'] == 1) and (row['imgur_thumbnail_url'] is not None or row['imgur_image_url'] is not None):
        # client.delete_image(img)
        # # These code snippets use an open-source library.
        # These code snippets use an open-source library. http://unirest.io/python
            response = unirest.delete("https://imgur-apiv3.p.mashape.com/3/image/{}".format(row['imgur_deletehash']),
                                      headers={
                "X-Mashape-Key": "y4mVnnNiZBmshBb9s7rh4DSw6K53p1T5SDujsnxxEUEvw62m4L",
                "Authorization": "Client-ID 999ee789e084f2e",
                "Accept": "text/plain"
              }
            )
            print response.body['status']

            if response.body['status'] == 200:
                print "was successful"
Esempio n. 3
0
 def test_delete(self):
     response = unirest.delete('http://httpbin.org/delete',
                               params={
                                   "name": "Mark",
                                   "nick": "thefosk"
                               })
     self.assertEqual(response.code, 200)
     self.assertEqual(response.body['data'], "nick=thefosk&name=Mark")
Esempio n. 4
0
    def postasyn(self, path, data=None, method="POST", callback=None):
        def post_cb(response):
            callback(response.body)

        path = '/{version}/{path}'.format(version=self.api_version, path=path)
        url = "%s%s" % (self.url, path)
        data = json.dumps(data).encode('utf-8')
        print("in _request:" + str(url))
        print("in _request:" + str(data))
        if method == "DELETE":
            unirest.delete(
                url,
                headers={"Content-Type": "application/json;charset=utf-8"},
                params=data,
                callback=post_cb)
        else:
            unirest.post(
                url,
                headers={"Content-Type": "application/json;charset=utf-8"},
                params=data,
                callback=post_cb)
Esempio n. 5
0
def execute(mthd, url, body_data=None):
    try:
        access_token = 'sq0atb-_ifJWXh-Jj15F004mRfJ6Q' #os.environ['SQUARE_ACCESS_TOKEN']
    except KeyError:
        raise Exception("Set the server environment variable SQUARE_ACCESS_TOKEN to that of your Square account.")
    if mthd == "GET":
        response = unirest.get(url, headers={ "Authorization": "Bearer "+access_token, "Accept": "application/json" })
    elif mthd == "POST":
        response = unirest.post(url, headers={ "Authorization": "Bearer "+access_token, "Accept": "application/json", "Content-Type": "application/json" }, params=body_data)
    elif mthd == "PUT":
        response = unirest.put(url, headers={ "Authorization": "Bearer "+access_token, "Accept": "application/json", "Content-Type": "application/json" }, params=body_data)
    elif mthd == "DELETE":
        response = unirest.delete(url, headers={ "Authorization": "Bearer "+access_token, "Accept": "application/json" })
    return response.body
    def delete_media_by_id(self,
                           id):
        """Does a DELETE request to /media/{id}.

        Delete media results. It returns the status of the operation.

        Args:
            id (string): The id of the media.

        Returns:
            MediaByIdResponse: Response from the API. 

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        # The base uri for api requests
        query_builder = Configuration.BASE_URI
 
        # Prepare query string for API call
        query_builder += "/media/{id}"

        # Process optional template parameters
        query_builder = APIHelper.append_url_with_template_parameters(query_builder, { 
            "id": id
        })

        # Validate and preprocess url
        query_url = APIHelper.clean_url(query_builder)

        #append custom auth authorization
        CustomAuthUtility.appendCustomAuthParams(headers)

        # Prepare and invoke the API call request to fetch the response
        unirest.timeout(20)
        response = unirest.delete(query_url, headers=headers)

        # Error handling using HTTP status codes
        if response.code < 200 or response.code > 206:  # 200 = HTTP OK
            print response.body
            raise APIException("HTTP Response Not OK", response.code, response.body) 
    
        # Try to cast response to desired type
        if isinstance(response.body, dict):
            print "Media ID Deleted"
Esempio n. 7
0
    def delete(access_token, document_id):
        """Delete a document that has been uploaded to a users account

        Args:
            access_token (str): The access token for the user account that has access to the document.
            document_id (str): The unique id of the document you want to delete.

        Returns:
            dict: The JSON response from the API {u'result': u'success'} or JSON representing an API error.
        """
        response = delete(Config().get_base_url() + '/document/' + document_id, headers={
            "Authorization": "Bearer " + access_token,
            "Accept": "application/json"
        })

        return response.body
Esempio n. 8
0
    def delete(access_token, subscription_id):
        """Deletes an event subscription with the given id

        Args:
            access_token (str): The access token of the account you want to delete the event subscriptiotn from.
            subscription_id (str): The unique id of the subscription being deleted.

        Returns:
            dict: The JSON response from the API with the id of the deleted subscription or an API error.
        """
        response = delete(Config().get_base_url() + '/event_subscription/' + subscription_id, headers={
            "Authorization": "Bearer " + access_token,
            "Accept": "application/json"
        })

        return response.body
Esempio n. 9
0
    def delete(access_token, document_id):
        """Delete a document that has been uploaded to a users account

        Args:
            access_token (str): The access token for the user account that has access to the document.
            document_id (str): The unique id of the document you want to delete.

        Returns:
            dict: The JSON response from the API {u'result': u'success'} or JSON representing an API error.
        """
        response = delete(Config().get_base_url() + '/document/' + document_id,
                          headers={
                              "Authorization": "Bearer " + access_token,
                              "Accept": "application/json"
                          })

        return response.body
Esempio n. 10
0
    def delete(access_token, subscription_id):
        """Deletes an event subscription with the given id

        Args:
            access_token (str): The access token of the account you want to delete the event subscriptiotn from.
            subscription_id (str): The unique id of the subscription being deleted.

        Returns:
            dict: The JSON response from the API with the id of the deleted subscription or an API error.
        """
        response = delete(Config().get_base_url() + '/event_subscription/' +
                          subscription_id,
                          headers={
                              "Authorization": "Bearer " + access_token,
                              "Accept": "application/json"
                          })

        return response.body
    def delete_occurrence_download_delete_cancel(self,
                                                 key):
        """Does a DELETE request to /occurrence/download/request/{key}.

        Cancels the download process.

        Args:
            key (string): Cancels the download process.

        Returns:
            void: Response from the API. 

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        # The base uri for api requests
        query_builder = Configuration.BASE_URI
 
        # Prepare query string for API call
        query_builder += "/occurrence/download/request/{key}"

        # Process optional template parameters
        query_builder = APIHelper.append_url_with_template_parameters(query_builder, { 
            "key": key
        })

        # Validate and preprocess url
        query_url = APIHelper.clean_url(query_builder)

        # Prepare headers
        headers = {
            "user-agent": "APIMATIC 2.0"
        }

        # Prepare and invoke the API call request to fetch the response
        response = unirest.delete(query_url, headers=headers, params={}, auth=(self.__user, self.__password))

        # Error handling using HTTP status codes
        if response.code < 200 or response.code > 206:  # 200 = HTTP OK
            raise APIException("HTTP Response Not OK", response.code, response.body) 
    def DeleteOneCustomers(self,
                pk):
        '''
        Delete one object

        :param pk: Required CustomerID 
        :type pk: string
        :returns: response from the API call
        :rType: CustomersModel 
        '''
    
        #prepare query string for API call
        queryBuilder = Configuration.BASEURI + "/Customers/{pk}"

        #process optional query parameters
        queryBuilder = APIHelper.appendUrlWithTemplateParameters(queryBuilder, { 
                     "pk": pk ,
            })

        #validate and preprocess url
        queryUrl = APIHelper.cleanUrl(queryBuilder)

        #prepare headers
        headers = {
            "User-Agent" : "APIMATIC 2.0",
            "Accept" : "application/json",
        }

        #prepare and invoke the API call request to fetch the response
        response = unirest.delete(queryUrl, headers=headers)

        #Error handling using HTTP status codes
        if response.code < 200 and response.code > 206: #200 = HTTP OK
            raise APIException("HTTP Response Not OK", response.code)     

        return response.body
Esempio n. 13
0
    def DeleteOneCustomers(self, pk):
        '''
        Delete one object

        :param pk: Required CustomerID 
        :type pk: string
        :returns: response from the API call
        :rType: CustomersModel 
        '''

        #prepare query string for API call
        queryBuilder = Configuration.BASEURI + "/Customers/{pk}"

        #process optional query parameters
        queryBuilder = APIHelper.appendUrlWithTemplateParameters(
            queryBuilder, {
                "pk": pk,
            })

        #validate and preprocess url
        queryUrl = APIHelper.cleanUrl(queryBuilder)

        #prepare headers
        headers = {
            "User-Agent": "APIMATIC 2.0",
            "Accept": "application/json",
        }

        #prepare and invoke the API call request to fetch the response
        response = unirest.delete(queryUrl, headers=headers)

        #Error handling using HTTP status codes
        if response.code < 200 and response.code > 206:  #200 = HTTP OK
            raise APIException("HTTP Response Not OK", response.code)

        return response.body
Esempio n. 14
0
 def delete(self, id):
     res = unirest.delete(self.__monta_url(id), headers=self.__monta_headers())
     return self.__monta_retorno(res)
Esempio n. 15
0
print 'Retrieve replica sets of the user'
print '%s\n%s\n%s' % (response.code, response.headers, response.body)


# Retrieve Replica Set.

response = unirest.get("http://localhost:" + REST_PORT + "/replicaset/-4727115044472165798")

print 'Retrieve a replica set'
print '%s\n%s\n%s' % (response.code, response.headers, response.body)


# Delete Replica Set.

response = unirest.delete("http://localhost:" + REST_PORT + "/replicaset/12?replicaSetID=-5896416803618323002")

print 'Delete a replica set'
print '%s\n%s\n%s' % (response.code, response.headers, response.body)


# Replace Replica Set.

print 'Replace a replica set'
response = unirest.post("http://localhost:" + REST_PORT + "/replicaset/-4727115044472165798", headers={ "Accept": "application/json" }, params={"iStudyInstanceUID" : "1.3.6.1.4.1.14519.5.2.1.4591.4001.151679082681232740021018262895", "iSeriesInstanceUID" : "1.3.6.1.4.1.14519.5.2.1.4591.4001.179004339156422100336233996679" })

print '%s\n%s\n%s' % (response.code, response.headers, response.body)


# Append Replica Set.
Esempio n. 16
0

'''
Delete images
'''

# to_delete = ["692LfMR1HKotuic","nbxl2ZAcOTO2eoz", "nrsNcrYqUV0A9rH"]
to_delete = engine.execute("SELECT deletehash FROM imgur")
for img in to_delete:
  # client.delete_image(img)
# # These code snippets use an open-source library.
  # These code snippets use an open-source library. http://unirest.io/python
  response = unirest.delete("https://imgur-apiv3.p.mashape.com/3/image/{}".format(img[0]),
    headers={
      "X-Mashape-Key": "huYA3ztRaxmshy95Mcj4dTmVrMTHp1iQ858jsn3jpASEst4dig",
      "Authorization": "Client-ID 67d854ceaa5af4c",
      "Accept": "text/plain"
    }
  )
  print response.body['status']

  if response.body['status'] == 200:
    # engine.execute("DELETE FROM imgur WHERE deletehash = {}".format(img[0]))
    query = '''DELETE FROM imgur WHERE deletehash = %s'''
    engine.execute(query, (img[0]))




'''
'''
def deleteWebhook(accountId, apiToken, webhookId):
    response = unirest.delete("%s%s/webhooks/%s" % (url, accountId, webhookId),
                              auth=('', apiToken))
    print response.raw_body
    def appendCustomAuthParams(method='GET',
                               query_url=Configuration.BASE_URI,
                               body='',
                               headers={}):
        """
        Appends the necessary OAuth credentials for making this authorized call

        :param method: The outgoing request method
        :type string: GET, PUT, PATCH, POST, DELETE
        :param query_url: URL to make the request to
        :type string:
        :param body: request payload
        :type string:
        :param headers: The out going request to access the resource
        :type dict: Header dictionary
        """

        timestamp = dt.datetime.utcnow().replace(microsecond=0).isoformat()
        headers['X-Timestamp'] = timestamp

        body_hash = ""
        if body:
            # TODO: implement conditions for body transposing into a md5 hash
            #       and accommodate for handling form data
            body_hash = hashlib.md5(body).hexdigest() if body != '' else ''

        parsed_url = urlparse(query_url)
        qpd = dict(parse_qsl(parsed_url.query))
        qp = sorted(qpd.items())
        ordered_qp = urlencode(qp)

        canonical_uri = '{0}://{1}{2}\n{3}'.format(parsed_url.scheme,
                                                   parsed_url.netloc,
                                                   parsed_url.path,
                                                   ordered_qp)

        tokens = (timestamp, method, body_hash, canonical_uri)
        message_string = u'\n'.join(tokens).encode('utf-8')
        signature = hmac.new(Configuration.password, message_string, 
                             digestmod=hashlib.sha1).hexdigest()

        url = canonical_uri.replace('\n', '?')

        response = ''
        if method == 'GET':
            response = unirest.get(url,
                                   auth=(Configuration.username, signature),
                                   headers=headers,
                                   params=body)
        elif method == 'PUT':
            response = unirest.put(url,
                                   auth=(Configuration.username, signature),
                                   headers=headers,
                                   params=body)
        elif method == 'POST':
            response = unirest.post(url,
                                    auth=(Configuration.username, signature),
                                    headers=headers,
                                    params=body)
        elif method == 'PATCH':
            response = unirest.patch(url,
                                     auth=(Configuration.username, signature),
                                     headers=headers,
                                     params=body)
        elif method == 'DELETE':
            response = unirest.delete(url,
                                      auth=(Configuration.username, signature),
                                      headers=headers,
                                      params=body)
        else:
            raise ValueError('Invalid HTTP Method was used.')

        return response
    def appendCustomAuthParams(method='GET',
                               query_url=Configuration.BASE_URI,
                               body='',
                               headers={}):
        """
        Appends the necessary OAuth credentials for making this authorized call

        :param method: The outgoing request method
        :type string: GET, PUT, PATCH, POST, DELETE
        :param query_url: URL to make the request to
        :type string:
        :param body: request payload
        :type string:
        :param headers: The out going request to access the resource
        :type dict: Header dictionary
        """

        timestamp = dt.datetime.utcnow().replace(microsecond=0).isoformat()
        headers['X-Timestamp'] = timestamp

        body_hash = ""
        if body:
            # TODO: implement conditions for body transposing into a md5 hash
            #       and accommodate for handling form data
            body_hash = hashlib.md5(body).hexdigest() if body != '' else ''

        parsed_url = urlparse(query_url)
        qpd = dict(parse_qsl(parsed_url.query))
        qp = sorted(qpd.items())
        ordered_qp = urlencode(qp)

        canonical_uri = '{0}://{1}{2}\n{3}'.format(parsed_url.scheme,
                                                   parsed_url.netloc,
                                                   parsed_url.path, ordered_qp)

        tokens = (timestamp, method, body_hash, canonical_uri)
        message_string = u'\n'.join(tokens).encode('utf-8')
        signature = hmac.new(Configuration.password,
                             message_string,
                             digestmod=hashlib.sha1).hexdigest()

        url = canonical_uri.replace('\n', '?')

        response = ''
        if method == 'GET':
            response = unirest.get(url,
                                   auth=(Configuration.username, signature),
                                   headers=headers,
                                   params=body)
        elif method == 'PUT':
            response = unirest.put(url,
                                   auth=(Configuration.username, signature),
                                   headers=headers,
                                   params=body)
        elif method == 'POST':
            response = unirest.post(url,
                                    auth=(Configuration.username, signature),
                                    headers=headers,
                                    params=body)
        elif method == 'PATCH':
            response = unirest.patch(url,
                                     auth=(Configuration.username, signature),
                                     headers=headers,
                                     params=body)
        elif method == 'DELETE':
            response = unirest.delete(url,
                                      auth=(Configuration.username, signature),
                                      headers=headers,
                                      params=body)
        else:
            raise ValueError('Invalid HTTP Method was used.')

        return response
Esempio n. 20
0
	def test_delete(self):
		response = unirest.delete('http://httpbin.org/delete', params={"name":"Mark", "nick":"thefosk"})
		self.assertEqual(response.code, 200)
		self.assertEqual(response.body['form']['name'], "Mark")
                self.assertEqual(response.body['form']['nick'], "thefosk")
Esempio n. 21
0
 def test_delete(self):
     response = unirest.delete("http://httpbin.org/delete", params={"name": "Mark", "nick": "thefosk"})
     self.assertEqual(response.code, 200)
     self.assertEqual(response.body["data"], "nick=thefosk&name=Mark")