Python requests.post() Examples

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

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

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

Example 1
Project: BASS   Author: Cisco-Talos   File: bindiff.py    License: 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 2
Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: cisco_apic_em_1.py    License: MIT License 8 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 3
Project: marketo-rest-python   Author: jepcastelein   File: http_lib.py    License: 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
Project: BASS   Author: Cisco-Talos   File: bindiff.py    License: 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 5
Project: BASS   Author: Cisco-Talos   File: bindiff.py    License: 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 6
Project: video2commons   Author: toolforge   File: app.py    License: 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 7
Project: CyberTK-Self   Author: CyberTKR   File: channel.py    License: 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 8
Project: CyberTK-Self   Author: CyberTKR   File: channel.py    License: 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 9
Project: CyberTK-Self   Author: CyberTKR   File: channel.py    License: GNU General Public License v2.0 6 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 10
Project: CyberTK-Self   Author: CyberTKR   File: channel.py    License: 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 11
Project: CyberTK-Self   Author: CyberTKR   File: channel.py    License: 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 12
Project: CyberTK-Self   Author: CyberTKR   File: LineApi.py    License: 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 13
Project: fishroom   Author: tuna   File: gitter.py    License: 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 14
Project: fishroom   Author: tuna   File: photostore.py    License: 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 15
Project: KDD2019-HandsOn-Tutorial   Author: graph-knowledgegraph   File: 5.Recommendations.py    License: 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 16
Project: KDD2019-HandsOn-Tutorial   Author: graph-knowledgegraph   File: 5.Recommendations.py    License: 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 17
Project: InsightAgent   Author: insightfinder   File: verifyInsightCredentials.py    License: 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 18
Project: InsightAgent   Author: insightfinder   File: verifyInsightCredentials.py    License: 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 19
Project: InsightAgent   Author: insightfinder   File: getmetrics_hadoop.py    License: 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 20
Project: InsightAgent   Author: insightfinder   File: getmetrics_nfdump.py    License: 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 21
Project: InsightAgent   Author: insightfinder   File: getlogs_Pufa.py    License: 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 22
Project: jumpserver-python-sdk   Author: jumpserver   File: request.py    License: GNU General Public License v2.0 5 votes vote down vote up
def post(self, *args, **kwargs):
        kwargs['method'] = 'post'
        return self.do(*args, **kwargs) 
Example 23
Project: telegram-innovation-chatbot   Author: zaoldyeck   File: kkbox.py    License: MIT License 5 votes vote down vote up
def _get_token(self):
        response = requests.post(self.AUTH_URL, data={'grant_type': 'client_credentials'}, auth=(self.id, self.secret))
        response.raise_for_status()
        return response.json()['access_token'] 
Example 24
Project: telegram-innovation-chatbot   Author: zaoldyeck   File: olami.py    License: MIT License 5 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 25
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    License: MIT License 5 votes vote down vote up
def _isAsthamaPump(self, imageWidth, imageHeight, imageString):
        result = {}
        coordinates = {}
        metadata = {}
        isPresent = False

        try :
            self._printLogs("Sending Image To DL Server...", "NORMAL")

            url = DL_SERVER_URL
            payload = {
                        "imageWidth"   : imageWidth,
                        "imageHeight"  : imageHeight,
                        "image_string" : base64.b64encode(imageString),
                        "imageID"      : self.imageNo2d
                        }
            headers = {'content-type': 'application/json'}

            res = requests.post(url, data=json.dumps(payload), headers=headers)
            result = res.json()
            self._printLogs("[*] Sent to  : " + str(url), "OKBLUE")
            self._printLogs("[*] Response : " + str(result), "OKBLUE")

        except Exception, err:
            self._printLogs("Error Found on connecting to server : " + str(err), "FAIL")
            self._printLogs("+", "LINE") 
Example 26
Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: custom_module_2.py    License: MIT License 5 votes vote down vote up
def main():
    module = AnsibleModule(
      argument_spec = dict(
        host = dict(required=True),
        username = dict(required=True),
        password = dict(required=True)
      )
    )
    
    device = module.params.get('host')
    username = module.params.get('username')
    password = module.params.get('password')

    url='http://' + host + '/ins'
    switchuser=username
    switchpassword=password

    myheaders={'content-type':'application/json-rpc'}
    
    payload=[
      {
        "jsonrpc": "2.0",
        "method": "cli",
        "params": {
          "cmd": "show version",
          "version": 1.2
        },
        "id": 1
      }
    ]
    response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()

    version = response['result']['body']['sys_ver_str']
    data = json.dumps({"version": version})
    module.exit_json(changed=False, msg=str(data)) 
Example 27
Project: BASS   Author: Cisco-Talos   File: funcdb.py    License: GNU General Public License v2.0 5 votes vote down vote up
def add(self, db, **kwargs):
        db_data = db.data.copy()
        db_data["functions"] = _filter_functions(db.data["functions"], **kwargs)
        data = pickle.dumps(db_data)
        result = requests.post("{:s}/function".format(self.url), files = {"file": BytesIO(data)})
        if result.status_code != 200:
            raise RuntimeError("Request failed with status code {:d}".format(result.status_code)) 
Example 28
Project: BASS   Author: Cisco-Talos   File: funcdb.py    License: GNU General Public License v2.0 5 votes vote down vote up
def find_raw(self, db, **kwargs):
        db_data = db.data.copy()
        db_data["functions"] = _filter_functions(db.data["functions"], **kwargs)
        data = pickle.dumps(db_data)
        result = requests.post("{:s}/function/find/raw".format(self.url), files = {"file": BytesIO(data)})
        if result.status_code == 200:
            return True
        elif result.status_code == 404:
            return False
        else:
            raise RuntimeError("Request failed with status code {:d}".format(result.status_code)) 
Example 29
Project: BASS   Author: Cisco-Talos   File: funcdb.py    License: GNU General Public License v2.0 5 votes vote down vote up
def find_mnem(self, db, **kwargs):
        db_data = db.data.copy()
        db_data["functions"] = _filter_functions(db.data["functions"], **kwargs)
        data = pickle.dumps(db_data)
        result = requests.post("{:s}/function/find/mnem".format(self.url), files = {"file": BytesIO(data)})
        if result.status_code == 200:
            return True
        elif result.status_code == 404:
            return False
        else:
            raise RuntimeError("Request failed with status code {:d}".format(result.status_code)) 
Example 30
Project: BASS   Author: Cisco-Talos   File: whitelist.py    License: GNU General Public License v2.0 5 votes vote down vote up
def main(args, env):
    response = requests.post("{:s}/whitelist".format(args.url), files = {"file": open(args.sample, "rb")})
    if response.status_code != 200:
        print("Server returned error {:d}: {:s}".format(response.status_code, response.content))