Python pycurl.POSTFIELDS Examples

The following are 24 code examples of pycurl.POSTFIELDS(). 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 pycurl , or try the search function .
Example #1
Source File: psurl.py    From pscheduler with Apache License 2.0 6 votes vote down vote up
def url_post( url,          # GET URL
              params={},    # GET parameters
              data=None,    # Data to post
              content_type=None,  # Content type
              bind=None,    # Bind request to specified address
              json=True,    # Interpret result as JSON
              throw=True,   # Throw if status isn't 200
              timeout=None, # Seconds before giving up
              allow_redirects=True, #Allows URL to be redirected
              headers={},   # Hash of HTTP headers
              verify_keys=verify_keys_default  # Verify SSL keys
              ):
    """
    Post to a URL, returning whatever came back.
    """

    content_type, data = __content_type_data(content_type, headers, data)
    headers["Content-Type"] = content_type

    curl = PycURLRunner(url, params, bind, timeout, allow_redirects, headers, verify_keys)

    curl.curl.setopt(pycurl.POSTFIELDS, data)

    return curl(json, throw) 
Example #2
Source File: psurl.py    From pscheduler with Apache License 2.0 6 votes vote down vote up
def url_put( url,          # GET URL
             params={},    # GET parameters
             data=None,    # Data for body
             content_type=None,  # Content type
             bind=None,    # Bind request to specified address
             json=True,    # Interpret result as JSON
             throw=True,   # Throw if status isn't 200
             timeout=None, # Seconds before giving up
             allow_redirects=True, #Allows URL to be redirected
             headers={},   # Hash of HTTP headers
             verify_keys=verify_keys_default  # Verify SSL keys
             ):
    """
    PUT to a URL, returning whatever came back.
    """

    content_type, data = __content_type_data(content_type, headers, data)
    headers["Content-Type"] = content_type

    curl = PycURLRunner(url, params, bind, timeout, allow_redirects, headers, verify_keys)

    curl.curl.setopt(pycurl.CUSTOMREQUEST, "PUT")
    curl.curl.setopt(pycurl.POSTFIELDS, data)

    return curl(json, throw) 
Example #3
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 6 votes vote down vote up
def perform_fp(fp, method, url, header='', body=''):
    #logger.debug('perform: %s' % url)
    fp.setopt(pycurl.URL, url)

    if method == 'GET':
      fp.setopt(pycurl.HTTPGET, 1)

    elif method == 'POST':
      fp.setopt(pycurl.POST, 1)
      fp.setopt(pycurl.POSTFIELDS, body)

    elif method == 'HEAD':
      fp.setopt(pycurl.NOBODY, 1)

    else:
      fp.setopt(pycurl.CUSTOMREQUEST, method)

    headers = [h.strip('\r') for h in header.split('\n') if h]
    fp.setopt(pycurl.HTTPHEADER, headers)

    fp.perform() 
Example #4
Source File: server_post_install.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def send_REST_request(ip, port, object, payload):
    try:
        response = StringIO()
        headers = ["Content-Type:application/json"]
        url = "http://%s:%s/%s" %(
            ip, port, object)
        conn = pycurl.Curl()
        conn.setopt(pycurl.URL, url)
        conn.setopt(pycurl.HTTPHEADER, headers)
        conn.setopt(pycurl.POST, 1)
        conn.setopt(pycurl.POSTFIELDS, '%s'%json.dumps(payload))
        conn.setopt(pycurl.CUSTOMREQUEST, "PUT")
        conn.setopt(pycurl.WRITEFUNCTION, response.write)
        conn.perform()
        return response.getvalue()
    except:
        return None 
Example #5
Source File: utils.py    From falsy with MIT License 6 votes vote down vote up
def setup_curl_for_post(c, p, data_buf, headers=None, share=None):
    setup_curl_basic(c, p, data_buf, headers, share)
    httpheader = p.get('httpheader', ['Accept: application/json', "Content-type: application/json"])
    if httpheader:
        # c.setopt(pycurl.HEADER, p.get('header', 1))
        c.setopt(pycurl.HTTPHEADER, httpheader)
    post301 = getattr(pycurl, 'POST301', None)
    if post301 is not None:
        # Added in libcurl 7.17.1.
        c.setopt(post301, True)
    c.setopt(pycurl.POST, 1)
    postfields = p.get('postfields')
    if postfields:
        postfields = json.dumps(postfields, indent=2, ensure_ascii=False)
        c.setopt(pycurl.POSTFIELDS, postfields)
    return c 
Example #6
Source File: server_pre_install.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def send_REST_request(ip, port, object, payload):
    try:
        response = StringIO()
        headers = ["Content-Type:application/json"]
        url = "http://%s:%s/%s" %(
            ip, port, object)
        conn = pycurl.Curl()
        conn.setopt(pycurl.URL, url)
        conn.setopt(pycurl.HTTPHEADER, headers)
        conn.setopt(pycurl.POST, 1)
        conn.setopt(pycurl.POSTFIELDS, '%s'%json.dumps(payload))
        conn.setopt(pycurl.CUSTOMREQUEST, "PUT")
        conn.setopt(pycurl.WRITEFUNCTION, response.write)
        conn.perform()
        return response.getvalue()
    except:
        return None 
Example #7
Source File: smgr_provision_server.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def send_REST_request(ip, port, payload):
    try:
        response = StringIO()
        headers = ["Content-Type:application/json"]
        url = "http://%s:%s/server/provision" %(
            ip, port)
        conn = pycurl.Curl()
        conn.setopt(pycurl.URL, url)
        conn.setopt(pycurl.HTTPHEADER, headers)
        conn.setopt(pycurl.POST, 1)
        conn.setopt(pycurl.POSTFIELDS, '%s'%json.dumps(payload))
        conn.setopt(pycurl.WRITEFUNCTION, response.write)
        conn.perform()
        return response.getvalue()
    except:
        return None 
Example #8
Source File: sm_ansible_utils.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def send_REST_request(self, ip, port, endpoint, payload,
                          method='POST', urlencode=False):
        try:
            response = StringIO()
            headers = ["Content-Type:application/json"]
            url = "http://%s:%s/%s" %(ip, port, endpoint)
            conn = pycurl.Curl()
            if method == "PUT":
                conn.setopt(pycurl.CUSTOMREQUEST, method)
                if urlencode == False:
                    first = True
                    for k,v in payload.iteritems():
                        if first:
                            url = url + '?'
                            first = False
                        else:
                            url = url + '&'
                        url = url + ("%s=%s" % (k,v))
                else:
                    url = url + '?' + payload
            if self.logger:
                self.logger.log(self.logger.INFO,
                                "Sending post request to %s" % url)
            conn.setopt(pycurl.URL, url)
            conn.setopt(pycurl.HTTPHEADER, headers)
            conn.setopt(pycurl.POST, 1)
            if urlencode == False:
                conn.setopt(pycurl.POSTFIELDS, '%s'%json.dumps(payload))
            conn.setopt(pycurl.WRITEFUNCTION, response.write)
            conn.perform()
            return response.getvalue()
        except:
            return None 
Example #9
Source File: smgr_reimage_server.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def send_REST_request(ip, port, payload):
    try:
        response = StringIO()
        headers = ["Content-Type:application/json"]
        url = "http://%s:%s/server/reimage" %(
            ip, port)
        conn = pycurl.Curl()
        conn.setopt(pycurl.URL, url)
        conn.setopt(pycurl.HTTPHEADER, headers)
        conn.setopt(pycurl.POST, 1)
        conn.setopt(pycurl.POSTFIELDS, '%s'%json.dumps(payload))
        conn.setopt(pycurl.WRITEFUNCTION, response.write)
        conn.perform()
        return response.getvalue()
    except:
        return None 
Example #10
Source File: smgr_restart_server.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def send_REST_request(ip, port, payload):
    try:
        response = StringIO()
        headers = ["Content-Type:application/json"]
        url = "http://%s:%s/server/restart" %(
            ip, port)
        conn = pycurl.Curl()
        conn.setopt(pycurl.URL, url)
        conn.setopt(pycurl.HTTPHEADER, headers)
        conn.setopt(pycurl.POST, 1)
        conn.setopt(pycurl.POSTFIELDS, '%s'%json.dumps(payload))
        conn.setopt(pycurl.WRITEFUNCTION, response.write)
        conn.perform()
        return response.getvalue()
    except:
        return None
# end def send_REST_request 
Example #11
Source File: smgr_dhcp_event.py    From contrail-server-manager with Apache License 2.0 5 votes vote down vote up
def send_REST_request(ip, port, action, payload):
    try:
        url = "http://%s:%s/dhcp_event?action=%s" % (ip, port, action)
        headers = ["Content-Type:application/json"]

        conn = pycurl.Curl()
        conn.setopt(pycurl.TIMEOUT, 1)
        conn.setopt(pycurl.URL, url)
        conn.setopt(pycurl.HTTPHEADER, headers)
        conn.setopt(pycurl.POST, 1)
        conn.setopt(pycurl.POSTFIELDS, payload)
        conn.perform()
    except:
        return 
Example #12
Source File: test_bagofrequests.py    From pyaem with MIT License 5 votes vote down vote up
def test_request_post(self):

        curl = pycurl.Curl()
        curl.setopt = MagicMock()
        curl.perform = MagicMock()
        curl.getinfo = MagicMock(return_value=200)
        curl.close = MagicMock()
        pycurl.Curl = MagicMock(return_value=curl)

        method = 'post'
        url = 'http://localhost:4502/.cqactions.html'
        params = {'foo1': 'bar1', 'foo2': ['bar2a', 'bar2b']}
        handlers = {200: self._handler_dummy}

        result = pyaem.bagofrequests.request(method, url, params, handlers)

        curl.setopt.assert_any_call(pycurl.POST, 1)
        curl.setopt.assert_any_call(pycurl.POSTFIELDS, 'foo1=bar1&foo2=bar2a&foo2=bar2b')
        curl.setopt.assert_any_call(pycurl.URL, 'http://localhost:4502/.cqactions.html')
        curl.setopt.assert_any_call(pycurl.FOLLOWLOCATION, 1)
        curl.setopt.assert_any_call(pycurl.FRESH_CONNECT, 1)

        # 6 calls including the one with pycurl.WRITEFUNCTION
        self.assertEqual(curl.setopt.call_count, 6)

        curl.perform.assert_called_once_with()
        curl.getinfo.assert_called_once_with(pycurl.HTTP_CODE)
        curl.close.assert_called_once_with()

        self.assertEqual(result.is_success(), True)
        self.assertEqual(result.message, 'some dummy message')
        self.assertEqual(result.response['request']['method'], 'post')
        self.assertEqual(result.response['request']['url'], 'http://localhost:4502/.cqactions.html')
        self.assertEqual(result.response['request']['params'], params) 
Example #13
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def post(self, cgi, params):
        "Ship a POST request to a specified CGI, capture the response."
        self.set_option(pycurl.POST, 1)
        self.set_option(pycurl.POSTFIELDS, urllib_parse.urlencode(params))
        return self.__request(cgi) 
Example #14
Source File: transport.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request(self, url, method, body, headers):
            c = pycurl.Curl()
            c.setopt(pycurl.URL, str(url))
            if 'proxy_host' in self.proxy:
                c.setopt(pycurl.PROXY, self.proxy['proxy_host'])
            if 'proxy_port' in self.proxy:
                c.setopt(pycurl.PROXYPORT, self.proxy['proxy_port'])
            if 'proxy_user' in self.proxy:
                c.setopt(pycurl.PROXYUSERPWD, "%(proxy_user)s:%(proxy_pass)s" % self.proxy)
            self.buf = StringIO()
            c.setopt(pycurl.WRITEFUNCTION, self.buf.write)
            #c.setopt(pycurl.READFUNCTION, self.read)
            #self.body = StringIO(body)
            #c.setopt(pycurl.HEADERFUNCTION, self.header)
            if self.cacert:
                c.setopt(c.CAINFO, str(self.cacert)) 
            c.setopt(pycurl.SSL_VERIFYPEER, self.cacert and 1 or 0)
            c.setopt(pycurl.SSL_VERIFYHOST, self.cacert and 2 or 0)
            c.setopt(pycurl.CONNECTTIMEOUT, self.timeout/6) 
            c.setopt(pycurl.TIMEOUT, self.timeout)
            if method=='POST':
                c.setopt(pycurl.POST, 1)
                c.setopt(pycurl.POSTFIELDS, body)            
            if headers:
                hdrs = ['%s: %s' % (str(k), str(v)) for k, v in headers.items()]
                ##print hdrs
                c.setopt(pycurl.HTTPHEADER, hdrs)
            c.perform()
            ##print "pycurl perform..."
            c.close()
            return {}, self.buf.getvalue() 
Example #15
Source File: http.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def request(self, method, url, body=None):
        def makeRequest(ignored):
            curl = CurlRequestDriver.curl
            curl.reset()

            curl.setopt(pycurl.URL, url)
            curl.setopt(pycurl.HEADERFUNCTION, self.receiveHeaders)
            curl.setopt(pycurl.WRITEFUNCTION, self.buffer.write)

            curl.setopt(pycurl.CUSTOMREQUEST, method)

            if body is not None:
                curl.setopt(pycurl.POSTFIELDS, body)

            headers = []
            for key, value in six.iteritems(self.headers):
                headers.append("{}: {}".format(key, value))
            curl.setopt(pycurl.HTTPHEADER, headers)

            d = threads.deferToThread(curl.perform)
            d.addCallback(self.receive)
            return d

        def releaseLock(result):
            CurlRequestDriver.lock.release()

            # Forward the result to the next handler.
            return result

        d = CurlRequestDriver.lock.acquire()

        # Make the request once we acquire the semaphore.
        d.addCallback(makeRequest)

        # Release the semaphore regardless of how the request goes.
        d.addBoth(releaseLock)
        return d 
Example #16
Source File: client.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def get_URLencoded_poster(self):
        """Initialze a Curl object for a single POST request.

        Returns a tuple of initialized Curl and HTTPResponse objects.
        """
        data = urlparse.urlencode(self._data, True)
        c = pycurl.Curl()
        resp = HTTPResponse(self._encoding)
        c.setopt(c.URL, str(self._url))
        c.setopt(pycurl.POST, 1)
        c.setopt(pycurl.POSTFIELDS, data)
        c.setopt(c.WRITEFUNCTION, resp._body_callback)
        c.setopt(c.HEADERFUNCTION, resp._header_callback)
        headers = self._headers[:]
        headers.append(httputils.ContentType("application/x-www-form-urlencoded"))
        headers.append(httputils.ContentLength(str(len(data))))
        c.setopt(c.HTTPHEADER, map(str, headers))
        self._set_common(c)
        return c, resp 
Example #17
Source File: http_client.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def request(self, method, url, headers, post_data=None):
        s = util.StringIO.StringIO()
        curl = pycurl.Curl()

        if method == 'get':
            curl.setopt(pycurl.HTTPGET, 1)
        elif method == 'post':
            curl.setopt(pycurl.POST, 1)
            curl.setopt(pycurl.POSTFIELDS, post_data)
        else:
            curl.setopt(pycurl.CUSTOMREQUEST, method.upper())

        # pycurl doesn't like unicode URLs
        curl.setopt(pycurl.URL, util.utf8(url))

        curl.setopt(pycurl.WRITEFUNCTION, s.write)
        curl.setopt(pycurl.NOSIGNAL, 1)
        curl.setopt(pycurl.CONNECTTIMEOUT, 30)
        curl.setopt(pycurl.TIMEOUT, 80)
        curl.setopt(pycurl.HTTPHEADER, ['%s: %s' % (k, v)
                    for k, v in headers.iteritems()])
        if self._verify_ssl_certs:
            curl.setopt(pycurl.CAINFO, os.path.join(
                os.path.dirname(__file__), 'data/ca-certificates.crt'))
        else:
            curl.setopt(pycurl.SSL_VERIFYHOST, False)

        try:
            curl.perform()
        except pycurl.error, e:
            self._handle_request_error(e) 
Example #18
Source File: InstagramRegistration.py    From Instagram-API with MIT License 5 votes vote down vote up
def request(self, endpoint, post=None):
        buffer = BytesIO()

        ch = pycurl.Curl()
        ch.setopt(pycurl.URL, Constants.API_URL + endpoint)
        ch.setopt(pycurl.USERAGENT, self.userAgent)
        ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
        ch.setopt(pycurl.FOLLOWLOCATION, True)
        ch.setopt(pycurl.HEADER, True)
        ch.setopt(pycurl.VERBOSE, False)
        ch.setopt(pycurl.COOKIEFILE, os.path.join(self.IGDataPath, self.username, self.username + "-cookies.dat"))
        ch.setopt(pycurl.COOKIEJAR, os.path.join(self.IGDataPath, self.username, self.username + "-cookies.dat"))

        if post is not None:
            ch.setopt(pycurl.POST, True)
            ch.setopt(pycurl.POSTFIELDS, post)

        if self.proxy:
            ch.setopt(pycurl.PROXY, self.proxyHost)
            if self.proxyAuth:
                ch.setopt(pycurl.PROXYUSERPWD, self.proxyAuth)

        ch.perform()
        resp = buffer.getvalue()
        header_len = ch.getinfo(pycurl.HEADER_SIZE)
        header = resp[0: header_len]
        body = resp[header_len:]

        ch.close()

        if self.debug:
            print("REQUEST: " + endpoint)
            if post is not None:
                if not isinstance(post, list):
                    print("DATA: " + str(post))
            print("RESPONSE: " + body)

        return [header, json_decode(body)] 
Example #19
Source File: Checkpoint.py    From Instagram-API with MIT License 5 votes vote down vote up
def request(self, endpoint, headers=None, post=None, first=True):
        buffer = BytesIO()

        ch = pycurl.Curl()

        ch.setopt(pycurl.URL, endpoint)
        ch.setopt(pycurl.USERAGENT, self.userAgent)
        ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
        ch.setopt(pycurl.FOLLOWLOCATION, True)
        ch.setopt(pycurl.HEADER, True)
        if headers:
            ch.setopt(pycurl.HTTPHEADER, headers)

        ch.setopt(pycurl.VERBOSE, self.debug)
        ch.setopt(pycurl.SSL_VERIFYPEER, False)
        ch.setopt(pycurl.SSL_VERIFYHOST, False)
        ch.setopt(pycurl.COOKIEFILE, self.settingsPath + self.username + '-cookies.dat')
        ch.setopt(pycurl.COOKIEJAR, self.settingsPath + self.username + '-cookies.dat')

        if post:
            import urllib
            ch.setopt(pycurl.POST, len(post))
            ch.setopt(pycurl.POSTFIELDS, urllib.urlencode(post))

        ch.perform()
        resp = buffer.getvalue()
        header_len = ch.getinfo(pycurl.HEADER_SIZE)
        header = resp[0: header_len]
        body = resp[header_len:]
        ch.close()

        if self.debug:
            import urllib
            print("REQUEST: " + endpoint)
            if post is not None:
                if not isinstance(post, list):
                    print('DATA: ' + urllib.unquote_plus(json.dumps(post)))
            print("RESPONSE: " + body + "\n")

        return [header, json_decode(body)] 
Example #20
Source File: analyze_packages.py    From pyCAF with GNU General Public License v3.0 4 votes vote down vote up
def get_rh_sso(self):
        """
        Function wich used login and password to connect at www.redhat.com and return
        the "rh_sso" proxy used for request authentication.
        """
        self._logger.debug("RHEL rh_sso getting in progress...")
        username = self.config_server.redhat["login_username"]
        password = self.config_server.redhat["login_pass"]
        url = 'https://www.redhat.com/wapps/sso/login.html'
        values={'username':username,'password':password,'_flowId':'legacy-login-flow','redirect':'https://www.redhat.com/wapps/ugc/protected/account.html','failureRedirect':'http://www.redhat.com/wapps/sso/login.html'}
        data_post = urllib.urlencode(values)
      
        headers = Storage()
        
        c = pycurl.Curl()
        c.setopt(pycurl.URL, url)
#==============================================================================
#     DEBUG comments in order to use the Burp Proxy software 
#==============================================================================
    #c.setopt(pycurl.PROXY, '127.0.0.1')
    #c.setopt(pycurl.PROXYPORT, 8080)
    #c.setopt(pycurl.SSL_VERIFYPEER, 1)
    #c.setopt(pycurl.SSL_VERIFYHOST, 2)
    #c.setopt(pycurl.CAINFO, "/home/thierry/Divers/Burp/cacert.crt")
#==============================================================================
        c.setopt(pycurl.USERAGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0")
        c.setopt(pycurl.HTTPHEADER, ['Accept-Language: en-US,en;q=0.5',
                                     'Connection: keep-alive',
                                     'www.whitehouse.gov: 200'])
        c.setopt(pycurl.POST, 1)
        c.setopt(pycurl.POSTFIELDS, data_post)
        
        c.setopt(c.HEADERFUNCTION, headers.store)
        
        c.perform()
        c.close()
        headers = str(headers)
        
        expression = r"(?P<var1>.*)(?P<rh_sso>Set-Cookie: rh_sso=)(?P<sso_key>(?!\").*?)(?P<end>;)"
        header_lines = headers.split('\n')
        for head in header_lines:
            result_re = re.match(expression, head)
            
            if result_re is not None:
                sso_key = "rh_sso=" + str(result_re.group('sso_key'))
        self._logger.debug("rh_sso value : "+ str(sso_key))
        return sso_key 
Example #21
Source File: xcoin_api_client.py    From Coiner with Apache License 2.0 4 votes vote down vote up
def xcoinApiCall(self, endpoint, rg_params):
        # 1. Api-Sign and Api-Nonce information generation.
        # 2. Request related information from the Bithumb API server.
        #
        # - nonce: it is an arbitrary number that may only be used once.
        # - api_sign: API signature information created in various combinations values.

        endpoint_item_array = {
            "endpoint" : endpoint
        }

        uri_array = dict(endpoint_item_array, **rg_params) # Concatenate the two arrays.

        str_data = urllib.parse.urlencode(uri_array)

        nonce = self.usecTime()

        data = endpoint + chr(0) + str_data + chr(0) + nonce
        utf8_data = data.encode('utf-8')

        key = self.api_secret
        utf8_key = key.encode('utf-8')

        h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512)
        hex_output = h.hexdigest()
        utf8_hex_output = hex_output.encode('utf-8')

        api_sign = base64.b64encode(utf8_hex_output)
        utf8_api_sign = api_sign.decode('utf-8')


        curl_handle = pycurl.Curl()
        curl_handle.setopt(pycurl.POST, 1)
        #curl_handle.setopt(pycurl.VERBOSE, 1) # vervose mode :: 1 => True, 0 => False
        curl_handle.setopt(pycurl.POSTFIELDS, str_data)

        url = self.api_url + endpoint
        curl_handle.setopt(curl_handle.URL, url)
        curl_handle.setopt(curl_handle.HTTPHEADER, ['Api-Key: ' + self.api_key, 'Api-Sign: ' + utf8_api_sign, 'Api-Nonce: ' + nonce])
        curl_handle.setopt(curl_handle.WRITEFUNCTION, self.body_callback)
        curl_handle.perform()

        #response_code = curl_handle.getinfo(pycurl.RESPONSE_CODE) # Get http response status code.

        curl_handle.close()

        return (json.loads(self.contents)) 
Example #22
Source File: patator.py    From patator with GNU General Public License v2.0 4 votes vote down vote up
def perform_fp(fp, method, url, header='', body=''):
    #logger.debug('perform: %s' % url)
    fp.setopt(pycurl.URL, url)

    if method == 'GET':
      fp.setopt(pycurl.HTTPGET, 1)

    elif method == 'POST':
      fp.setopt(pycurl.POST, 1)
      fp.setopt(pycurl.POSTFIELDS, body)

    elif method == 'HEAD':
      fp.setopt(pycurl.NOBODY, 1)

    else:
      fp.setopt(pycurl.CUSTOMREQUEST, method)

    headers = [h.strip('\r') for h in header.split('\n') if h]
    fp.setopt(pycurl.HTTPHEADER, headers)

    fp.perform() 
Example #23
Source File: reqresp.py    From darkc0de-old-stuff with GNU General Public License v3.0 4 votes vote down vote up
def perform(self):
		self.__performHead=""
		self.__performBody=""

		conn=pycurl.Curl()
		conn.setopt(pycurl.SSL_VERIFYPEER,False)
		conn.setopt(pycurl.SSL_VERIFYHOST,1)
		conn.setopt(pycurl.URL,self.completeUrl)

		if self.__method or self.__userpass:
			if self.__method=="basic":
				conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
			elif self.__method=="ntlm":
				conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_NTLM)
			elif self.__method=="digest":
				conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
			conn.setopt(pycurl.USERPWD, self.__userpass)

		if self.__timeout:
			conn.setopt(pycurl.CONNECTTIMEOUT, self.__timeout)
			conn.setopt(pycurl.NOSIGNAL, 1)

		if self.__totaltimeout:
			conn.setopt(pycurl.TIMEOUT, self.__totaltimeout)
			conn.setopt(pycurl.NOSIGNAL, 1)

		conn.setopt(pycurl.WRITEFUNCTION, self.body_callback)
		conn.setopt(pycurl.HEADERFUNCTION, self.header_callback)

		if self.__proxy!=None:
			conn.setopt(pycurl.PROXY,self.__proxy)
			if self.__headers.has_key("Proxy-Connection"):
				del self.__headers["Proxy-Connection"]

		conn.setopt(pycurl.HTTPHEADER,self.__getHeaders())
		if self.method=="POST":
			conn.setopt(pycurl.POSTFIELDS,self.__postdata)
		conn.perform()

		rp=Response()
		rp.parseResponse(self.__performHead)
		rp.addContent(self.__performBody)

		self.response=rp

	######### ESTE conjunto de funciones no es necesario para el uso habitual de la clase 
Example #24
Source File: bagofrequests.py    From pyaem with MIT License 4 votes vote down vote up
def request(method, url, params, handlers, **kwargs):
    """Sends HTTP request to a specified URL.
    Parameters will be appended to URL automatically on HTTP get method.
    Response code will then be used to determine which handler should process the response.
    When response code does not match any handler, an exception will be raised.

    :param method: HTTP method (post, delete, get)
    :type method: str
    :param url: URL to send HTTP request to
    :type url: str
    :param params: Request parameters key-value pairs, use array value to represent multi parameters with the same name
    :type params: dict
    :param handlers: Response handlers key-value pairs, keys are response http code, values are callback methods
    :type handlers: dict
    :returns:  PyAemResult -- Result of the request containing status, response http code and body, and request info
    :raises: PyAemException
    """
    curl = pycurl.Curl()
    body_io = cStringIO.StringIO()

    if method == 'post':
        curl.setopt(pycurl.POST, 1)
        curl.setopt(pycurl.POSTFIELDS, urllib.urlencode(params, True))
    elif method == 'delete':
        curl.setopt(pycurl.CUSTOMREQUEST, method)
    elif method == 'head':
        curl.setopt(pycurl.HEADER, True)
        curl.setopt(pycurl.NOBODY, True)
    else:
        url = '{0}?{1}'.format(url, urllib.urlencode(params, True))

    curl.setopt(pycurl.URL, url)
    curl.setopt(pycurl.FOLLOWLOCATION, 1)
    curl.setopt(pycurl.FRESH_CONNECT, 1)
    curl.setopt(pycurl.WRITEFUNCTION, body_io.write)

    curl.perform()

    response = {
        'http_code': curl.getinfo(pycurl.HTTP_CODE),
        'body': body_io.getvalue(),
        'request': {
            'method': method,
            'url': url,
            'params': params
        }
    }

    curl.close()

    if response['http_code'] in handlers:
        return handlers[response['http_code']](response, **kwargs)
    else:
        handle_unexpected(response, **kwargs)