Python requests.post() Examples

The following are 30 code examples of requests.post(). 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: cisco_apic_em_1.py    From Mastering-Python-Networking-Second-Edition with MIT License 10 votes vote down vote up
def getTicket():
    # put the ip address or dns of your apic-em controller in this url
    url = "https://" + controller + "/api/v1/ticket"

    #the username and password to access the APIC-EM Controller
    payload = {"username":"usernae","password":"password"}

    #Content type must be included in the header
    header = {"content-type": "application/json"}

    #Performs a POST on the specified url to get the service ticket
    response= requests.post(url,data=json.dumps(payload), headers=header, verify=False)

    #convert response to json format
    r_json=response.json()

    #parse the json to get the service ticket
    ticket = r_json["response"]["serviceTicket"]

    return ticket 
Example #2
Source File: bindiff.py    From BASS with GNU General Public License v2.0 9 votes vote down vote up
def bindiff_export(self, sample, is_64_bit = True, timeout = None):
        """
        Load a sample into IDA Pro, perform autoanalysis and export a BinDiff database.
        :param sample: The sample's path
        :param is_64_bit: If the sample needs to be analyzed by the 64 bit version of IDA
        :param timeout: Timeout for the analysis in seconds
        :return: The file name of the exported bindiff database. The file needs
        to be deleted by the caller. Returns None on error.
        """

        data_to_send = {
            "timeout": timeout,
            "is_64_bit": is_64_bit}
        url = "%s/binexport" % next(self._urls)
        log.debug("curl -XPOST --data '%s' '%s'", json.dumps(data_to_send), url)
        response = requests.post(url, data = data_to_send, files = {os.path.basename(sample): open(sample, "rb")})
        if response.status_code == 200:
            handle, output = tempfile.mkstemp(suffix = ".BinExport")
            with os.fdopen(handle, "wb") as f:
                map(f.write, response.iter_content(1024))
            return output
        else:
            log.error("Bindiff server responded with status code %d: %s", response.status_code, response.content)
            return None 
Example #3
Source File: http_lib.py    From marketo-rest-python with MIT License 8 votes vote down vote up
def post(self, endpoint, args, data=None, files=None, filename=None,
             mode=None):
        if mode == 'nojsondumps':
            headers = {'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'}
            r = requests.post(endpoint, params=args, data=data, headers=headers)
        elif files is None:
            headers = {'Content-type': 'application/json; charset=utf-8'}
            r = requests.post(endpoint, params=args, json=data, headers=headers)
        elif files is not None:
            mimetype = mimetypes.guess_type(files)[0]
            file = {filename: (files, open(files, 'rb'), mimetype)}
            r = requests.post(endpoint, params=args, json=data, files=file)
        r_json = r.json()
        if r_json.get('success'):
            return r_json
        else:
            raise MarketoException(r_json['errors'][0]) 
Example #4
Source File: channel.py    From CyberTK-Self with GNU General Public License v2.0 7 votes vote down vote up
def like(self, mid, postid, likeType=1001):

        header = {
            "Content-Type" : "application/json",
            "X-Line-Mid" : self.mid,
            "x-lct" : self.channel_access_token,
        }

        payload = {
            "likeType" : likeType,
            "activityExternalId" : postid,
            "actorId" : mid
        }

        r = requests.post(
            "http://" + self.host + "/mh/api/v23/like/create.json?homeId=" + mid,
            headers = header,
            data = json.dumps(payload)
        )

        return r.json() 
Example #5
Source File: LineApi.py    From CyberTK-Self with GNU General Public License v2.0 6 votes vote down vote up
def post_image(self):
    try:
      self.image_b64()
    except Exception as e: raise Exception("Image cant be converted.");
    payload = "data=data:image/jpeg;base64," + self.b64img
    payload += '&filter=*&trial=4'
    header = {
      'Host':'whatanime.ga',
      'accept':'application/json, text/javascript, */*; q=0.01',
      'content-type':'application/x-www-form-urlencoded; charset=UTF-8',
      'origin':'https://whatanime.ga',
      'referer':'https://whatanime.ga/',
      'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
      'x-requested-with':'XMLHttpRequest',
    }
    r = requests.post('https://whatanime.ga/search', data=payload, headers=header)
    if r.status_code == 200:
      return r.json()
    else:
      raise Exception("Post failed.") 
Example #6
Source File: 5.Recommendations.py    From KDD2019-HandsOn-Tutorial with MIT License 6 votes vote down vote up
def comparetext (text1, text2, api=__ls_api):
  """
  Computes the semantic similarity between two given text strings. Returns a score between [-1, 1].

  Parameters
  ----------
  text1 : string

  text2 : string

  api : string (default=cloud release endpoint)
      The endpoint you wish to hit for the concept labeling task. Default is the release version of the Microsoft Academic Language Similarity API.    
  """
  body = {
    "Text1": text1,
    "Text2": text2
  }
  endpoint = api + 'comparetext'
  resp = requests.post(endpoint, json=body)
  assert resp.status_code == 200, endpoint + " failed with status: " + str(resp.status_code)
  return float(resp.content) 
Example #7
Source File: 5.Recommendations.py    From KDD2019-HandsOn-Tutorial with MIT License 6 votes vote down vote up
def comparelabel (text, concept_id, api=__ls_api):
  """
  Computes the semantic similarity between the given text string and a concept. Returns a score between [-1, 1].

  Parameters
  ----------
  text : string

  id : int
      The id of the concept to compare against the given text.

  api : string (default=cloud release endpoint)
      The endpoint you wish to hit for the concept labeling task. Default is the release version of the Microsoft Academic Language Similarity API.    
  """
  body = {
    "Text": text,
    "Label": concept_id
  }
  endpoint = api + 'comparelabel'
  resp = requests.post(endpoint, json=body)
  assert resp.status_code == 200, endpoint + " failed with status: " + str(resp.status_code)
  return float(resp.content)

# COMMAND ---------- 
Example #8
Source File: app.py    From video2commons with GNU General Public License v3.0 6 votes vote down vote up
def querylanguage(auth):
    """Query user's language that's available on v2c."""
    default = 'en'

    r = requests.post(
        url=api_url.replace('index.php', 'api.php'),
        data={
            'action': 'query',
            'format': 'json',
            'meta': 'userinfo',
            'uiprop': 'options'
        },
        auth=auth
    )

    try:
        language = r.json()['query']['userinfo']['options']['language']
    except (NameError, KeyError):
        return default

    if not language:
        return default

    return language 
Example #9
Source File: verifyInsightCredentials.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def sendData():
    global projectName
    global userInsightfinder
    global licenseKey
    alldata["userName"] = userInsightfinder
    alldata["operation"] = "verify"
    alldata["licenseKey"] = licenseKey
    alldata["projectName"] = projectName
    json_data = json.dumps(alldata)
    #print json_data
    url = serverUrl + "/api/v1/agentdatahelper"
    print serverUrl
    try:
        response = requests.post(url, data = json.loads(json_data))
    except requests.ConnectionError, e:
        print "Connection failure : " + str(e)
        print "Verification with InsightFinder credentials Failed"
        sys.exit(1) 
Example #10
Source File: verifyInsightCredentials.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def sendData():
    global projectName
    global userInsightfinder
    global licenseKey
    alldata["userName"] = userInsightfinder
    alldata["operation"] = "verify"
    alldata["licenseKey"] = licenseKey
    alldata["projectName"] = projectName
    json_data = json.dumps(alldata)
    #print json_data
    url = serverUrl + "/api/v1/agentdatahelper"
    print serverUrl
    try:
        response = requests.post(url, data = json.loads(json_data))
    except requests.ConnectionError, e:
        print "Connection failure : " + str(e)
        print "Verification with InsightFinder credentials Failed"
        sys.exit(1) 
Example #11
Source File: photostore.py    From fishroom with GNU General Public License v3.0 6 votes vote down vote up
def upload_image(self, filename=None, filedata=None, **kwargs) -> str:
        if filedata is None:
            files = {"image": open(filename, 'rb')}
        else:
            files = {"image": filedata}

        try:
            r = requests.post(self.url, files=files, timeout=5)
        except requests.exceptions.Timeout:
            logger.error("Timeout uploading to VimCN")
            return None
        except:
            logger.exception("Unknown errror uploading to VimCN")
            return None
        if not r.ok:
            return None
        return r.text.strip() 
Example #12
Source File: getmetrics_hadoop.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    """Sends metric data to InsightFinder backend"""
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example #13
Source File: channel.py    From CyberTK-Self with GNU General Public License v2.0 6 votes vote down vote up
def new_post(self, text):

        header = {
            "Content-Type": "application/json",
            "User-Agent" : self.UA,
            "X-Line-Mid" : self.mid,
            "x-lct" : self.channel_access_token,
        }

        payload = {
            "postInfo" : { "readPermission" : { "type" : "ALL" } },
            "sourceType" : "TIMELINE",
            "contents" : { "text" : text }
        }

        r = requests.post(
            "http://" + self.host + "/mh/api/v24/post/create.json",
            headers = header,
            data = json.dumps(payload)
        )

        return r.json() 
Example #14
Source File: channel.py    From CyberTK-Self with GNU General Public License v2.0 6 votes vote down vote up
def postPhoto(self,text,path):
        header = {
            "Content-Type": "application/json",
            "User-Agent" : self.UA,
            "X-Line-Mid" : self.mid,
            "x-lct" : self.channel_access_token,
        }

        payload = {
            "postInfo" : { "readPermission" : { "type" : "ALL" } },
            "sourceType" : "TIMELINE",
            "contents" : { "text" : text ,"media" :  [{u'objectId': u'F57144CF9ECC4AD2E162E68554D1A8BD1a1ab0t04ff07f6'}]}
        }
        r = requests.post(
            "http://" + self.host + "/mh/api/v24/post/create.json",
            headers = header,
            data = json.dumps(payload)
        )

        return r.json() 
Example #15
Source File: getmetrics_nfdump.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def sendData(metricData):
    sendDataTime = time.time()
    # prepare data for metric streaming agent
    toSendDataDict = {}
    toSendDataDict["metricData"] = json.dumps(metricData)
    toSendDataDict["licenseKey"] = agentConfigVars['licenseKey']
    toSendDataDict["projectName"] = agentConfigVars['projectName']
    toSendDataDict["userName"] = agentConfigVars['userName']
    toSendDataDict["instanceName"] = socket.gethostname().partition(".")[0]
    toSendDataDict["samplingInterval"] = str(int(reportingConfigVars['reporting_interval'] * 60))
    toSendDataDict["agentType"] = "nfdump"

    toSendDataJSON = json.dumps(toSendDataDict)
    logger.debug("TotalData: " + str(len(bytearray(toSendDataJSON))))

    #send the data
    postUrl = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(postUrl, data=json.loads(toSendDataJSON))
    if response.status_code == 200:
        logger.info(str(len(bytearray(toSendDataJSON))) + " bytes of data are reported.")
        updateLastSentFiles(pcapFileList)
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - sendDataTime)) 
Example #16
Source File: channel.py    From CyberTK-Self with GNU General Public License v2.0 6 votes vote down vote up
def comment(self, mid, postid, text):
        header = {
            "Content-Type" : "application/json",
            "X-Line-Mid" : self.mid,
            "x-lct" : self.channel_access_token,
        }

        payload = {
            "commentText" : text,
            "activityExternalId" : postid,
            "actorId" : mid
        }

        r = requests.post(
            "http://" + self.host + "/mh/api/v23/comment/create.json?homeId=" + mid,
            headers = header,
            data = json.dumps(payload)
        )

        return r.json() 
Example #17
Source File: bindiff.py    From BASS with GNU General Public License v2.0 6 votes vote down vote up
def compare(self, primary, secondary, timeout = None):
        """
        Run BinDiff on the two BinDiff databases.
        :param primary: The first BinExport database
        :param secondary: The second BinExport database
        :param timeout: Timeout for the command in seconds
        :returns: The directory name of the directory with the generated data on the shared volume
        """

        url = "%s/compare" % next(self._urls)
        log.debug("curl -XPOST --form 'timeout=%s' --form 'primary=@%s' --form 'secondary=@%s' '%s'", str(timeout), primary, secondary, url)
        response = requests.post(url, data = {"timeout": timeout}, \
                files = {"primary": open(primary, "rb"), "secondary": open(secondary, "rb")})

        if response.status_code == 200:
            handle, path = tempfile.mkstemp(suffix = ".bindiff.sqlite3")
            with os.fdopen(handle, "wb") as f:
                map(f.write, response.iter_content(1024))
            return path
        else:
            log.error("Bindiff server responded with status code %d: %s", response.status_code, response.content)
            return None 
Example #18
Source File: bindiff.py    From BASS with GNU General Public License v2.0 6 votes vote down vote up
def pickle_export(self, sample, is_64_bit = True, timeout = None):
        """
        Load a sample into IDA Pro, perform autoanalysis and export a pickle file. 
        :param sample: The sample's path
        :param is_64_bit: If the sample needs to be analyzed by the 64 bit version of IDA
        :param timeout: Timeout for the analysis in seconds
        :return: The file name of the exported pickle database. The file needs
        to be deleted by the caller. Returns None on error.
        """

        data_to_send = {
            "timeout": timeout,
            "is_64_bit": is_64_bit}
        url = "%s/pickle" % next(self._urls)
        log.debug("curl -XPOST --data '%s' '%s'", json.dumps(data_to_send), url)
        response = requests.post(url, data = data_to_send, files = {os.path.basename(sample): open(sample, "rb")})
        if response.status_code == 200:
            handle, output = tempfile.mkstemp(suffix = ".pickle")
            with os.fdopen(handle, "wb") as f:
                map(f.write, response.iter_content(1024))
            return output
        else:
            log.error("Bindiff server responded with status code %d: %s", response.status_code, response.content)
            return None 
Example #19
Source File: getlogs_Pufa.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    #for backend so this is the camel case in to_send_data_dict
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = config_vars['license_key']
    to_send_data_dict["projectName"] = config_vars['project_name']
    to_send_data_dict["userName"] = config_vars['user_name']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(config_vars['sampling_interval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['server_url'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.error("Failed to send data.")
    logger.info("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example #20
Source File: channel.py    From CyberTK-Self with GNU General Public License v2.0 6 votes vote down vote up
def createAlbum(self,gid,name):
        header = {
                    "Content-Type": "application/json",
                    "User-Agent" : self.UA,
                    "X-Line-Mid" : self.mid,
                    "x-lct" : self.channel_access_token,
        }
        payload = {
                "type" : "image",
                "title" : name
        }
        r = requests.post(
            "http://" + self.host + "/mh/album/v3/album?count=1&auto=0&homeId=" + gid,
            headers = header,
            data = json.dumps(payload)
        )
        return r.json() 
Example #21
Source File: gitter.py    From fishroom with GNU General Public License v3.0 6 votes vote down vote up
def _must_post(self, api, data=None, json=None, timeout=10, **kwargs):
        if data is not None:
            kwargs['data'] = data
        elif json is not None:
            kwargs['json'] = json
        else:
            kwargs['data'] = {}
        kwargs['timeout'] = timeout

        try:
            r = requests.post(api, **kwargs)
            return r
        except requests.exceptions.Timeout:
            logger.error("Timeout requesting Gitter")
        except KeyboardInterrupt:
            raise
        except:
            logger.exception("Unknown error requesting Gitter")
        return None 
Example #22
Source File: olami.py    From telegram-innovation-chatbot with MIT License 6 votes vote down vote up
def nli(self, text, cusid=None):
        response = requests.post(self.URL, params=self._gen_parameters('nli', text, cusid))
        response.raise_for_status()
        response_json = response.json()
        if response_json['status'] != 'ok':
            raise NliStatusError("NLI responded status != 'ok': {}".format(response_json['status']))
        else:
            nli_obj = response_json['data']['nli'][0]
            return self.intent_detection(nli_obj) 
Example #23
Source File: photostore.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def upload_image(self, filename=None, filedata=None, **kwargs):
        if filedata is None:
            with open(filename, 'rb') as f:
                b64img = b64encode(f.read())
        else:
            b64img = b64encode(filedata)

        headers = {"Authorization": "Client-ID %s" % self.client_id}
        try:
            r = requests.post(
                self.url,
                headers=headers,
                data={
                    'image': b64img,
                    'type': 'base64',
                },
                timeout=5,
            )
        except requests.exceptions.Timeout:
            logger.error("Timeout uploading to Imgur")
            return None
        except:
            logger.exception("Unknown errror uploading to Imgur")
            return None

        try:
            ret = json.loads(r.text)
        except:
            return None
        if ret.get('status', None) != 200 or ret.get('success', False) != True:
            logger.error(
                "Error: Imgur returned error, {}".format(ret.get('data', ''))
            )
            return None

        link = ret.get('data', {}).get('link', None)
        return link if link is None else re.sub(r'^http:', 'https:', link) 
Example #24
Source File: textstore.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def new_paste(self, text, sender, **kwargs) -> str:
        data = {
            'vimcn': text,
        }
        try:
            r = requests.post(self.api_url, data=data, timeout=5)
        except requests.exceptions.Timeout:
            logger.error("Timeout uploading to Vinergy")
            return None

        if r.text.startswith("http"):
            return r.text.strip()

        return None 
Example #25
Source File: telegram.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def send_msg(self, peer, content, sender=None, escape=True, rich_text=None,
                 **kwargs):
        for r in self.nickuser_regexes:
            m = r.match(content)
            if m is None:
                continue
            nick = m.group("nick")
            username = self.nick_store.get_username(nick)
            if username is None:
                continue
            content = r.sub(r'\g<pre>@{}\g<post>'.format(username), content)

        if rich_text:
            content = self.formatRichText(rich_text, escape=escape)
        elif escape:
            content = html.escape(content)

        # print(repr(content))

        tmpl = self.msg_tmpl(sender)
        api = self.api_base + "/sendMessage"

        data = {
            'chat_id': int(peer),
            'text': tmpl.format(sender=sender, content=content),
            'parse_mode': 'HTML',
        }
        if 'telegram' in kwargs:
            for k, v in kwargs['telegram'].items():
                data[k] = v
        self._must_post(api, json=data) 
Example #26
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 #27
Source File: 4.NameEntityRecognition.py    From KDD2019-HandsOn-Tutorial with MIT License 5 votes vote down vote up
def ner (text, api=__ner_api):
    resp = requests.post(__ner_api, json=text)
    assert resp.status_code == 200
    respj = json.loads(resp.content.decode('utf-8'))
    return list(zip(respj['input'].split(), respj['output'].split()))

# COMMAND ---------- 
Example #28
Source File: textstore.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def new_paste(self, text, sender, **kwargs) -> str:

        ts = kwargs["date"] + kwargs["time"] \
            if "date" in kwargs and "time" in kwargs \
            else get_now().strftime("%Y%m%d%H%M")

        filename = "{sender}.{ts}.txt".format(
            sender=sender,
            ts=ts
        )
        data = {
            'api_option': "paste",
            'api_dev_key': self.api_dev_key,
            'api_paste_code': text,
            'api_paste_name': filename,
        }
        try:
            r = requests.post(self.api_url, data=data, timeout=5)
        except requests.exceptions.Timeout:
            logger.error("Timeout uploading to Pastebin")
            return None

        if r.text.startswith("http"):
            return r.text.strip()

        return None 
Example #29
Source File: getmessages_kafka2.py    From InsightAgent with Apache License 2.0 5 votes vote down vote up
def send_request(url, mode='GET', failure_message='Failure!', success_message='Success!', **request_passthrough):
    """ sends a request to the given url """
    # determine if post or get (default)
    req = requests.get
    if mode.upper() == 'POST':
        req = requests.post

    for i in range(ATTEMPTS):
        try:
            response = req(url, **request_passthrough)
            if response.status_code == httplib.OK:
                logger.info(success_message)
                return response
            else:
                logger.warn(failure_message)
                logger.debug('Response Code: {}\nTEXT: {}'.format(
                    response.status_code, response.text))
        # handle various exceptions
        except requests.exceptions.Timeout:
            logger.exception('Timed out. Reattempting...')
            continue
        except requests.exceptions.TooManyRedirects:
            logger.exception('Too many redirects.')
            break
        except requests.exceptions.RequestException as e:
            logger.exception('Exception ' + str(e))
            break

    logger.error('Failed! Gave up after {} attempts.'.format(i))
    return -1 
Example #30
Source File: getlogs_servicenow.py    From InsightAgent with Apache License 2.0 5 votes vote down vote up
def send_request(url, mode='GET', failure_message='Failure!', success_message='Success!', **request_passthrough):
    """ sends a request to the given url """
    # determine if post or get (default)
    req = requests.get
    if mode.upper() == 'POST':
        req = requests.post

    global REQUESTS
    REQUESTS.update(request_passthrough)
    #logger.debug(REQUESTS)

    for i in range(ATTEMPTS):
        try:
            response = req(url, **request_passthrough)
            if response.status_code == httplib.OK:
                logger.info(success_message)
                return response
            else:
                logger.warn(failure_message)
                logger.debug('Response Code: {}\nTEXT: {}'.format(
                    response.status_code, response.text))
        # handle various exceptions
        except requests.exceptions.Timeout:
            logger.exception('Timed out. Reattempting...')
            continue
        except requests.exceptions.TooManyRedirects:
            logger.exception('Too many redirects.')
            break
        except requests.exceptions.RequestException as e:
            logger.exception('Exception ' + str(e))
            break

    logger.error('Failed! Gave up after {} attempts.'.format(i + 1))
    return -1