Python requests.request() Examples

The following are code examples for showing how to use requests.request(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: turbot_utils   Author: mosburn   File: account.py    BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def get_aws_access_key(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, turbot_user_id, api_version):
    """ Gets the federated access keys for a specified account

    :return: Returns the access key, secret key and session token for an account"""
    api_method = "POST"
    api_url = "/api/%s/accounts/%s/users/%s/awsCredentials" % (api_version, turbot_account, turbot_user_id)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    responseObj = json.loads(response.text)

    akey = responseObj['accessKeyId']
    skey = responseObj['secretAccessKey']
    token = responseObj['sessionToken']

    return (akey, skey, token) 
Example 2
Project: rebel-framework   Author: reb311ion   File: request.py    GNU General Public License v3.0 7 votes vote down vote up
def send(self,method,url,params=None,data=None,headers=None):
		if headers is None: headers={}
		headers['User-Agent'] = Request.agent
		try:
			session = requests.Session()
			req = urllib3.disable_warnings(
				urllib3.exceptions.InsecureRequestWarning
				)
			req = requests.request(
				method = method.upper(),
				url = url,
				params = params,
				data = data,
				allow_redirects = True,
				verify = False  )
			return req
		except Exception as e:
			exit(warn('Failed to establish a new connection')) 
Example 3
Project: securionpay-python   Author: securionpay   File: resource.py    MIT License 6 votes vote down vote up
def request(method, path, params=None):
        url = api.url.rstrip("/") + path
        data = {"params" if method in ["GET", "DELETE"] else "json": params}
        resp = requests.request(method, url, auth=(api.private_key, ""), **data)

        json = resp.json()
        if resp.status_code == 200:
            return json
        error = json.get("error")
        if error is None:
            raise api.SecurionPayException("Internal error", None, json, None, None)
        raise api.SecurionPayException(
            error.get("type"),
            error.get("code"),
            error.get("message"),
            error.get("charge_id"),
            error.get("blacklist_rule_id"),
        ) 
Example 4
Project: spqrel_tools   Author: LCAS   File: util.py    MIT License 6 votes vote down vote up
def parse_image(image):
    """Parse the image smartly and return metadata for request.

    First check whether the image is a URL or a file path or a file-like object
    and return corresponding metadata.

    Args:
        image: A URL or a file path or a file-like object represents an image.

    Returns:
        a three-item tuple consist of HTTP headers, binary data and json data
        for POST.
    """
    if hasattr(image, 'read'):  # When image is a file-like object.
        headers = {'Content-Type': 'application/octet-stream'}
        data = image.read()
        return headers, data, None
    elif os.path.isfile(image):  # When image is a file path.
        headers = {'Content-Type': 'application/octet-stream'}
        data = open(image, 'rb').read()
        return headers, data, None
    else:  # Defailt treat it as a URL (string).
        headers = {'Content-Type': 'application/json'}
        json = {'url': image}
        return headers, None, json 
Example 5
Project: pnp   Author: HazardDede   File: http.py    MIT License 6 votes vote down vote up
def push(self, url, method, fail_on_error, envelope, payload):  # pylint: disable=arguments-differ
        if isinstance(payload, (dict, list, tuple)):
            try:
                payload = json.dumps(payload)
            except:  # pylint: disable=bare-except
                pass
        resp = requests.request(method, url, data=str(payload))
        if fail_on_error and not 200 <= resp.status_code <= 299:
            raise PushExecutionError(
                "{method} of '{url}' failed with status code = '{status_code}'".format(
                    method=method,
                    url=url,
                    status_code=resp.status_code
                )
            )
        if not self.provide_response:
            return {'data': payload, **envelope} if envelope else payload

        try:
            return dict(status_code=resp.status_code, is_json=True, data=resp.json())
        except ValueError:
            # No valid json, try text
            return dict(status_code=resp.status_code, is_json=False, data=resp.text) 
Example 6
Project: flasky   Author: RoseOu   File: client.py    MIT License 6 votes vote down vote up
def get_response(args, config_dir):
    """Send the request and return a `request.Response`."""

    requests_kwargs = get_requests_kwargs(args)

    if args.debug:
        sys.stderr.write('\n>>> requests.request(%s)\n\n'
                         % pformat(requests_kwargs))

    if not args.session and not args.session_read_only:
        response = requests.request(**requests_kwargs)
    else:
        response = sessions.get_response(
            args=args,
            config_dir=config_dir,
            session_name=args.session or args.session_read_only,
            requests_kwargs=requests_kwargs,
            read_only=bool(args.session_read_only),
        )

    return response 
Example 7
Project: tvdbsimple   Author: phate89   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def refresh_token(self):
        """
        Refresh the current token set in the module.

        Returns the new obtained valid token for the API.
        """
        self._set_token_header()

        response = requests.request(
            'GET', self._get_complete_url('refresh_token'),
            headers=self._headers)

        response.raise_for_status()
        jsn = response.json()
        if 'token' in jsn:
            from . import KEYS
            KEYS.API_TOKEN = jsn['token']
            return KEYS.API_TOKEN
        return '' 
Example 8
Project: tvdbsimple   Author: phate89   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def _request(self, method, path, params=None, payload=None, forceNewToken=False, cleanJson = True):
        self._set_token_header(forceNewToken)
        
        url = self._get_complete_url(path)

        response = requests.request(
            method, url, params=params, 
            data=json.dumps(payload) if payload else payload,
            headers=self._headers)
        
        if response.status_code == 200:
            response.encoding = 'utf-8'
            jsn = response.json()
            if cleanJson and 'data' in jsn:
                return jsn['data']
            return jsn
        elif not forceNewToken:
            return self._request(method=method, path=path, params=params, payload=payload, forceNewToken=True)
        try:
            raise Exception(response.json()['Error'])
        except:
            response.raise_for_status() 
Example 9
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: client.py    Apache License 2.0 6 votes vote down vote up
def _authenticate(self):
        if self.auth_result:
            return self.auth_result

        auth_uri = self.auth_uri
        headers = {'X-Auth-User': self.auth_user,
                   'X-Auth-Key': self.auth_key,
                   'X-Auth-Project-Id': self.project_id}
        response = self.request(auth_uri,
                                headers=headers)

        http_status = response.status_code
        LOG.debug("%(auth_uri)s => code %(http_status)s",
                  {'auth_uri': auth_uri, 'http_status': http_status})

        if http_status == 401:
            raise OpenStackApiAuthenticationException(response=response)

        self.auth_result = response.headers
        return self.auth_result 
Example 10
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: trusted_filter.py    Apache License 2.0 6 votes vote down vote up
def _do_request(self, method, action_url, body, headers):
        # Connects to the server and issues a request.
        # :returns: result data
        # :raises: IOError if the request fails

        action_url = "https://%s:%s%s/%s" % (self.host, self.port,
                                             self.api_url, action_url)
        try:
            res = requests.request(method, action_url, data=body,
                                   headers=headers, cert=self.cert,
                                   verify=self.verify)
            status_code = res.status_code
            if status_code in (requests.codes.OK,
                               requests.codes.CREATED,
                               requests.codes.ACCEPTED,
                               requests.codes.NO_CONTENT):
                try:
                    return requests.codes.OK, jsonutils.loads(res.text)
                except (TypeError, ValueError):
                    return requests.codes.OK, res.text
            return status_code, None

        except requests.exceptions.RequestException:
            return IOError, None 
Example 11
Project: PyFlume   Author: ChrisMandich   File: __init__.py    MIT License 6 votes vote down vote up
def token_request(self, payload):
        """Request Authorization Payload."""
        headers = {"content-type": "application/json"}
        response = requests.request(
            "POST",
            URL_OAUTH_TOKEN,
            json=payload,
            headers=headers
            )

        LOGGER.debug("Token Payload: %s", payload)
        LOGGER.debug("Token Response: %s", response.text)

        # Check for response errors.
        _response_error(
            f"Can't get token for user {self._creds['username']}",
            response
            )

        return json.loads(response.text)["data"][0] 
Example 12
Project: PyFlume   Author: ChrisMandich   File: __init__.py    MIT License 6 votes vote down vote up
def get_devices(self):
        """Return all available devices from Flume API."""
        url = f"https://api.flumetech.com/users/\
        {self._flume_auth.user_id}/devices"

        querystring = {"user": "false", "location": "false"}
        response = requests.request(
            "GET",
            url,
            headers=self._flume_auth.authorization_header,
            params=querystring
            )

        LOGGER.debug("get_devices Response: %s", response.text)

        # Check for response errors.
        _response_error("Impossible to retreive devices", response)

        return json.loads(response.text)["data"] 
Example 13
Project: turbot_utils   Author: mosburn   File: find_set_options.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_cluster_id(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification):
    """ Gets the cluster id
    # TODO: put this in cluster.py
    """
    api_method = "GET"
    api_url = "/api/v1/cluster"

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    # Convert the response JSON into a Python object
    responseObj = json.loads(response.text)
    urn = responseObj['urn']

    return urn 
Example 14
Project: turbot_utils   Author: mosburn   File: find_set_options.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_option_list(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, urn):
    """ Gets the turbot option list

    """
    api_method = "GET"
    api_url = "/api/v1/resources/" + urn + "/options/"

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    options_obj = json.loads(response.text)

    return options_obj['items'] 
Example 15
Project: turbot_utils   Author: mosburn   File: find_set_options.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_set_option(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, urn, set_option):
    """ gets the set options"""

    api_method = "GET"
    api_url = "/api/v1/resources/" + urn + "/options/" + set_option


    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    options_obj = json.loads(response.text)

    for child in options_obj['children']:
        print(child) 
Example 16
Project: turbot_utils   Author: mosburn   File: create_system_ssh_key.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_user_ssh_keys(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_user_id):
    """ Sets user access AKIA key pairs for a specified account

    NOTE: This requires a Cluster role Turbot/Owner or higher in order to work.
    """
    api_method = "POST"
    api_url = "/api/v1/users/%s/sshKeys" % (turbot_user_id)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    responseObj = json.loads(response.text)
    return(responseObj['privateKey']) 
Example 17
Project: turbot_utils   Author: mosburn   File: guardrails.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_guardrail_list(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account_urn, api_version):
    """ Gets the list of guardrails

    :returns: Returns a list of the guardrails"""

    api_method = "GET"
    api_url = "/api/%s/resources/%s/options" % (api_version, turbot_account_urn)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    responseObj = json.loads(response.text)

    return responseObj['items'] 
Example 18
Project: turbot_utils   Author: mosburn   File: billing.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_account_bill(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, accountId, api_version):
    """ Gets the month to date charges for a given account

    """
    import requests
    import json
    import urllib.parse
    api_method = "GET"
    api_url = "/api/%s/accounts/%s/aws/estimatedCharges" % (api_version, accountId)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    # Convert the response JSON into a Python object
    responseObj = json.loads(response.text)

    print(responseObj['charges']['monthToDate']) 
Example 19
Project: turbot_utils   Author: mosburn   File: account.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete_user_access_keys(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, turbot_user_id, akey, api_version):
    """ Sets user access AKIA key pairs for a specified account

    NOTE: This requires a Cluster role Turbot/Owner or higher in order to work.
    """
    api_method = "DELETE"
    api_url = "/api/%s/accounts/%s/users/%s/awsAccessKeys/%s" % (api_version, turbot_account, turbot_user_id, akey)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    ) 
Example 20
Project: turbot_utils   Author: mosburn   File: account.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_user_access_keys(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, turbot_user_id, api_version):
    """ Sets user access AKIA key pairs for a specified account

    NOTE: This requires a Cluster role Turbot/Owner or higher in order to work.
    """
    api_method = "POST"
    api_url = "/api/%s/accounts/%s/users/%s/awsAccessKeys" % (api_version, turbot_account, turbot_user_id)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    responseObj = json.loads(response.text)
    akey = responseObj['accessKeyId']
    skey = responseObj['secretAccessKey']
    return (akey, skey) 
Example 21
Project: turbot_utils   Author: mosburn   File: account.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_account_tags(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, api_version):
    """ Sets user access AKIA key pairs for a specified account

    NOTE: This requires a Cluster role Turbot/Owner or higher in order to work.
    """
    api_method = "GET"
    api_url = "/api/%s/accounts/%s/" % (api_version, turbot_account)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    responseObj = json.loads(response.text)

    # If the account does not have tags, return false for an easy way to test later
    if 'tags' in responseObj:
        return responseObj['tags']
    else:
        return False 
Example 22
Project: turbot_utils   Author: mosburn   File: account.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_user_to_account(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host,userarn, permissions, urn, api_version):
    ''' Adds a user to account with Grant'''
    import requests
    import json
    import urllib.parse
    # Set to the required API request type and location
    api_url = "/api/%s/resources/%s/grants/%s" % (api_version, urn, permissions)
    data = {"identityUrn":  userarn, "activate": True}

    response = requests.post(
        json=data,
        url=urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key)

    )

    # Convert the response JSON into a Python object and store it if we need it
    responseObj = json.loads(response.text) 
Example 23
Project: turbot_utils   Author: mosburn   File: account.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete_user_grant(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host,userarn, permissions, urn, api_version):
    ''' Adds a user to account with Grant'''
    import requests
    import json
    import urllib.parse
    # Set to the required API request type and location
    api_method = "DELETE"
    api_url = "/api/%s/resources/%s/grants/%s/%s" % (api_version, urn, permissions,userarn)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    ) 
Example 24
Project: turbot_utils   Author: mosburn   File: notifications.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_guardrails_for_account(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, api_version):
    """ This returns the tick items notification stream from an account not the guardrail notifications"""
    api_method = "GET"
    api_url = "/api/%s/resources/%s/guardrails" % (api_version, turbot_account)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        },

    )

    responseObj = json.loads(response.text)

    return (responseObj['items']) 
Example 25
Project: turbot_utils   Author: mosburn   File: notifications.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_guardrail_violation(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, alarm_urn, api_version):
    """ This returns the tick items notification stream from an account not the guardrail notifications"""
    api_method = "GET"
    api_url = "/api/%s/resources/%s/guardrails/%s/notifications" % (api_version, turbot_account, alarm_urn)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        },

    )

    responseObj = json.loads(response.text)

    return (responseObj) 
Example 26
Project: pyatn-client   Author: ATNIO   File: atn.py    MIT License 6 votes vote down vote up
def call_dbot_api(self, dbot_address: str, uri: str, method: str, **requests_kwargs) -> Response:
        """Send the API's HTTP request

        Channel will be auto created if no channel or be topuped if
        insufficient balance in channel.
        The deposit value is determined by `deposit_strategy`.
        A signature of balance will be sent to DBot server to pay the price of the API.

        :param dbot_address: address of the DBot contract
        :param uri: uri of the endpoint
        :param method: method of the endpoint
        :param requests_kwargs: the other args for http request is same with `requests`
        :return: :class:`Response <Response>` object, http response of the API
        :rtype: requests.Response
        """
        dbot_address = Web3.toChecksumAddress(dbot_address)
        price = self.get_price(dbot_address, uri, method)
        channel = self._get_suitable_channel(dbot_address, price)
        channel.create_transfer(price)
        domain = self.get_dbot_domain(dbot_address)
        dbot_url = domain if domain.lower().startswith('http') else 'http://{}'.format(domain)
        url = '{}/call/{}/{}'.format(dbot_url, dbot_address, remove_slash_prefix(uri))
        return self._request(channel, method, url, **requests_kwargs) 
Example 27
Project: FHIRmaker   Author: sglanger   File: download_data.py    Apache License 2.0 6 votes vote down vote up
def getPatients(self):
	######################################
	# Purpose: dump all patients on this
	# 	EMR. 
	#	
	##########################################
		mod = 'download_data.py:FHIR:getPatients'
		addon = 'Patient/'
		url1 = self.url + addon

		#	cmd = 'curl --request GET  --url url --header Accept: "application/json" --header apikey: api_key ' 
		#print url1

		import requests
		response = requests.request("GET", url1, headers=self.headers)
		return  response.text 
Example 28
Project: FHIRmaker   Author: sglanger   File: download_data.py    Apache License 2.0 6 votes vote down vote up
def getConditions(self, site, cond) :
	######################################
	# Purpose: dump Condition resources 
	# 	that match site and condition
	#	
	# https://smilecdr.com/docs/current/tutorial_and_tour/fhir_search_queries.html
	##########################################
		mod = 'download_data.py:FHIR:getCondition'
		#addon = 'Condition?_bodySite=' + site + '&_content=' + cond		# gives odd results
		addon = 'Condition?_content=' + site + '&_content=' + cond
		url1 = self.url + addon

		#print (mod, url1)
		import requests, json
		response = requests.request("GET", url1, headers=self.headers)
		return  json.loads(response.text) 
Example 29
Project: FHIRmaker   Author: sglanger   File: download_data.py    Apache License 2.0 6 votes vote down vote up
def getPatients(self):
	######################################
	# Purpose: get list of all patients in
	# 		VNA
	#	
	##########################################
		mod = 'download_data.py:DCMweb:getStudies'
		# according to this link the below should get a result
		# https://docs.google.com/spreadsheets/d/e/2PACX-1vSBEymDKGZgskFEFF6yzge5JovGHPK_FIbEnW5a6SWUbPkX06tkoObUHh6T1XQhgj-HqFd0AWSnVFOv/pubhtml?gid=1094535210&single=true

		addon = 'patients/'

		url1 = self.url + addon

		import requests
		response = requests.request("GET", url1, headers=self.headers)
		return  response.text 
Example 30
Project: python-wordpress-json   Author: stylight   File: __init__.py    MIT License 5 votes vote down vote up
def _request(self, method_name, **kw):
        method, endpoint, params, data, json, headers = self._prepare_req(
            method_name, **kw
        )

        http_response = requests.request(
            method,
            self.site + endpoint,
            auth=self.auth,
            params=params,
            data=data,
            json=json,
            headers=headers
        )

        if http_response.status_code not in [200, 201]:
            if 'application/json' in http_response.headers.get('Content-Type'):
                code = http_response.json().get('code')
                message = http_response.json().get('message')
            else:
                code = http_response.status_code
                message = http_response.text
            raise WordpressError(" ".join([
                str(http_response.status_code),
                str(http_response.reason),
                ":",
                '[{code}] {message}'.format(code=code, message=message)
            ]))
        elif 'application/json' in http_response.headers.get('Content-Type'):
            return http_response.json()
        else:
            raise WordpressError(" ".join([
                "Expected JSON response but got",
                http_response.headers.get('Content-Type')])) 
Example 31
Project: securionpay-python   Author: securionpay   File: resource.py    MIT License 5 votes vote down vote up
def _get(self, path, params=None):
        return self.request("GET", path, params) 
Example 32
Project: securionpay-python   Author: securionpay   File: resource.py    MIT License 5 votes vote down vote up
def _post(self, path, params=None):
        return self.request("POST", path, params) 
Example 33
Project: securionpay-python   Author: securionpay   File: resource.py    MIT License 5 votes vote down vote up
def _delete(self, path, params=None):
        return self.request("DELETE", path, params) 
Example 34
Project: spqrel_tools   Author: LCAS   File: util.py    MIT License 5 votes vote down vote up
def request(method, url, data=None, json=None, headers=None, params=None):
    # pylint: disable=too-many-arguments
    """Universal interface for request."""

    # Make it possible to call only with short name (without _BASE_URL).
    if not url.startswith('https://'):
        url = _BASE_URL + url

    # Setup the headers with default Content-Type and Subscription Key.
    headers = headers or {}
    if 'Content-Type' not in headers:
        headers['Content-Type'] = 'application/json'
    headers['Ocp-Apim-Subscription-Key'] = Key.get()

    response = requests.request(method, url, params=params, data=data,
                                json=json, headers=headers)

    # Handle result and raise custom exception when something wrong.
    result = None
    # `person_group.train` return 202 status code for success.
    if response.status_code not in (200, 202):
        print('status_code: {}'.format(response.status_code))
        print('response: {}'.format(response.text))
        error_msg = response.json()['error']
        raise CognitiveFaceException(
            response.status_code,
            error_msg.get('code'),
            error_msg.get('message'))

    # Prevent `reponse.json()` complains about empty response.
    if response.text:
        result = response.json()
    else:
        result = {}

    return result 
Example 35
Project: tvdbsimple   Author: phate89   File: base.py    GNU General Public License v3.0 5 votes vote down vote up
def get_token(self, forceNew=False):
        """
        Get the existing token or creates it if it doesn't exist.
        Returns the API token.

        If `forceNew` is true  the function will do a new login to retrieve the token.
        """
        from . import KEYS
        if not KEYS.API_TOKEN or forceNew:
            if not KEYS.API_KEY:
                raise APIKeyError

            if hasattr(self,"USER") and hasattr(self,"USER_KEY"):
                data = {"apikey": KEYS.API_KEY, "username": self.USER, "userkey": self.USER_KEY}
            else:
                data={"apikey": KEYS.API_KEY}

            response = requests.request(
                    'POST', self._get_complete_url('login'), 
                    data=json.dumps(data), 
                    headers=self._headers)
            if response.status_code == 200:
                KEYS.API_TOKEN = response.json()['token']
            else:
                error = "Unknown error while authenticating. Check your api key or your user/userkey"
                try:
                    error = response.json()['Error']
                except:
                    pass
                raise AuthenticationError(error)
        return KEYS.API_TOKEN 
Example 36
Project: jdcloud-sdk-python   Author: jdcloud-api   File: jdcloudclient.py    Apache License 2.0 5 votes vote down vote up
def send(self, request):
        if self.__config is None:
            raise ClientException('Miss config object')
        if self.__credential is None:
            raise ClientException('Miss credential object')
        if request is None:
            raise ClientException('Miss request object')
        if request.parameters is None:
            raise ClientException('Miss parameters in request')

        region = self.__get_region_id(request)

        try:
            header = self.__merge_headers(request.header)
            token = header.get(const.JDCLOUD_SECURITY_TOKEN, '')

            param_builder = self.__builder_map[request.method]()
            url = param_builder.build_url(request, self.__config.scheme, self.__config.endpoint)
            body = param_builder.build_body(request)
            self.__logger.log(INFO, 'url=' + url)
            self.__logger.log(INFO, 'body=' + body)

            signer = Signer(self.__logger)
            signer.sign(method=request.method, region=region, uri=url,
                        headers=header, data=body, credential=self.__credential,
                        security_token=token, service=self.__service_name)
            self.__logger.log(INFO, header)

            resp = requests.request(request.method, url, data=body, headers=header,
                                    timeout=self.__config.timeout)
            self.__logger.log(INFO, resp.content)

            return self.__process_response(request.method, resp)
        except Exception as expt:
            msg = traceback.format_exc()
            self.__logger.log(ERROR, msg)
            raise expt 
Example 37
Project: jdcloud-sdk-python   Author: jdcloud-api   File: jdcloudclient.py    Apache License 2.0 5 votes vote down vote up
def __get_region_id(self, request):
        if isinstance(request.parameters, dict):
            if 'regionId' in request.parameters and request.parameters['regionId'] is not None:
                return request.parameters['regionId']
        else:
            if hasattr(request.parameters, 'regionId') and request.parameters.regionId is not None:
                return request.parameters.regionId

        return 'jdcloud-api'  # when no region, use this value to fill field for sign 
Example 38
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: client.py    Apache License 2.0 5 votes vote down vote up
def request(self, url, method='GET', body=None, headers=None):
        _headers = {'Content-Type': 'application/json'}
        _headers.update(headers or {})

        response = requests.request(method, url, data=body, headers=_headers)
        return response 
Example 39
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: client.py    Apache License 2.0 5 votes vote down vote up
def api_request(self, relative_uri, check_response_status=None,
                    strip_version=False, **kwargs):
        auth_result = self._authenticate()

        # NOTE(justinsb): httplib 'helpfully' converts headers to lower case
        base_uri = auth_result['x-server-management-url']
        if strip_version:
            # NOTE(vish): cut out version number and tenant_id
            base_uri = '/'.join(base_uri.split('/', 3)[:-1])

        full_uri = '%s/%s' % (base_uri, relative_uri)

        headers = kwargs.setdefault('headers', {})
        headers['X-Auth-Token'] = auth_result['x-auth-token']
        if self.microversion:
            headers['X-OpenStack-Nova-API-Version'] = self.microversion

        response = self.request(full_uri, **kwargs)

        http_status = response.status_code
        LOG.debug("%(relative_uri)s => code %(http_status)s",
                  {'relative_uri': relative_uri, 'http_status': http_status})

        if check_response_status:
            if http_status not in check_response_status:
                if http_status == 404:
                    raise OpenStackApiNotFoundException(response=response)
                elif http_status == 401:
                    raise OpenStackApiAuthorizationException(response=response)
                else:
                    raise OpenStackApiException(
                        message="Unexpected status code",
                        response=response)

        return response 
Example 40
Project: facebook-wda   Author: openatx   File: __init__.py    MIT License 5 votes vote down vote up
def httpdo(url, method="GET", data=None):
    """
    thread safe http request
    """
    p = urlparse(url)
    with namedlock(p.scheme+"://"+p.netloc):
        return _unsafe_httpdo(url, method, data) 
Example 41
Project: facebook-wda   Author: openatx   File: __init__.py    MIT License 5 votes vote down vote up
def _unsafe_httpdo(url, method='GET', data=None):
    """
    Do HTTP Request
    """
    start = time.time()
    if DEBUG:
        body = json.dumps(data) if data else ''
        print("Shell: curl -X {method} -d '{body}' '{url}'".format(
            method=method.upper(), body=body or '', url=url))

    try:
        response = requests.request(method,
                                    url,
                                    json=data,
                                    timeout=HTTP_TIMEOUT)
    except (requests.exceptions.ConnectionError,
            requests.exceptions.ReadTimeout) as e:
        raise

    if DEBUG:
        ms = (time.time() - start) * 1000
        print('Return ({:.0f}ms): {}'.format(ms, response.text))

    try:
        retjson = response.json()
        retjson['status'] = retjson.get('status', 0)
        r = convert(retjson)
        if r.status != 0:
            raise WDARequestError(r.status, r.value)
        return r
    except JSONDecodeError:
        if response.text == "":
            raise WDAEmptyResponseError(method, url, data)
        raise WDAError(method, url, response.text) 
Example 42
Project: douyin   Author: luocaiwei   File: dlib.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def api_service(route, token="", method="get", data=None, content_type="application/json",proxy=None):
    resp = requests.request(method=method, url="{0}/{1}/{2}".format(API_EP_DOUYIN, route, token), data=data,
                            headers={"Content-Type": content_type}, verify=False,proxies=proxy)
    if token != "" and resp.headers.get("x-token") != token:
        raise Exception(resp.headers.get("x-token"))
    elif resp.headers.get("x-token-times") == "0":
        raise Exception(resp.content)
    data = resp.content.decode("utf-8")
    return json.loads(data) 
Example 43
Project: turbot_utils   Author: mosburn   File: find_delete_users.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_grants(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, namespace, api_version):
    account_list = []
    api_method = "GET"
    api_url = "/api/%s/resources/%s/grants" % (api_version, namespace)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    # Convert the response JSON into a Python object
    responseObj = json.loads(response.text)

    for obj in responseObj['items']:
        if 'user' in obj:
            common_name = obj['user']['displayName']
        else:
            # Not all accounts have user displayname, most commonly [email protected]'s
            dummy, common_name = obj['identityUrn'].split('::user:')

        if '_DELETED' in common_name:
            print('Former employee %s found in account %s' % (common_name, namespace))
        account_list.append(common_name)
    return account_list 
Example 44
Project: turbot_utils   Author: mosburn   File: delete_ssh_keys_for_user.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_fingerprint(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_user_id, finger):
    api_method = "DELETE"
    api_url = "/api/v1/users/%s/sshKeys/%s" % (turbot_user_id, finger)
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    ) 
Example 45
Project: turbot_utils   Author: mosburn   File: aggrigrate_notifications_for_all.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_notifications(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, namespace, api_version):
    """ Gets the turbot notification for account
    
    :param turbot_host: turbot host
    :param turbot_api_access_key: turbot access key
    :param turbot_api_secret_key: turbot secret key
    :param turbot_host_certificate_verification: should be true
    :param namespace: the turbot namespace to look for alarms
    :param api_version: api version
    :return: Returns notification_list of all active notifications
    """
    api_method = "GET"
    api_url = "/api/%s/resources/%s/controls?filter=state:alarm,error" % (api_version, namespace)
    notification_list = []
    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    responseObj = json.loads(response.text)
    for notification in responseObj['items']:
        notification_list.append(notification['alarmUrn'])
    return notification_list 
Example 46
Project: turbot_utils   Author: mosburn   File: guardrails.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_guardrail(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account_urn, guardrail, api_version):
    """ Gets a guardrail

    :returns: returns a guardrail setting """

    api_method = "GET"
    api_url = "/api/%s/resources/%s/options/%s" % (api_version, turbot_account_urn, guardrail)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    responseObj = json.loads(response.text)
    print(responseObj['value'])
    return responseObj['value'] 
Example 47
Project: turbot_utils   Author: mosburn   File: cluster.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_cluster_id(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, api_version):
    """ Gets the cluster id
    # TODO: put this in cluster.py
    """
    import requests
    import json
    import urllib.parse
    api_method = "GET"
    api_url = "/api/%s/cluster" % (api_version)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    # Convert the response JSON into a Python object
    responseObj = json.loads(response.text)
    urn = responseObj['urn']

    return urn 
Example 48
Project: turbot_utils   Author: mosburn   File: cluster.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_turbot_account_ids(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, api_version):
    """ Gets the current turbot account names

    :return: Returns a dict of turbot account names as turbot_id:AWSaccount
    """
    import requests
    import json
    import urllib.parse
    # Set to the required API request type and location
    accounts = {}
    api_method = "GET"
    api_url = "/api/%s/accounts" % (api_version)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    # Convert the response JSON into a Python object
    responseObj = json.loads(response.text)

    if responseObj['items']:
        # A user may not have permission to list all accounts
        for obj in responseObj['items']:
            accounts[obj['id']] = obj['awsAccountId']

    return accounts 
Example 49
Project: turbot_utils   Author: mosburn   File: cluster.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_aws_account_ids(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, api_version):
    import requests
    import json
    import urllib.parse
    """ Gets the current turbot account names

    :return: Returns a list of turbot account names as accounts
    """
    # Set to the required API request type and location
    accounts = []
    api_method = "GET"
    api_url = "/api/%s/accounts" % (api_version)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    # Convert the response JSON into a Python object
    responseObj = json.loads(response.text)

    for obj in responseObj['items']:
        accounts.append(obj['awsAccountId'].zfill(12))

    return accounts 
Example 50
Project: turbot_utils   Author: mosburn   File: cluster.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_account_titles(turbot_api_access_key, turbot_api_secret_key,turbot_host_certificate_verification, turbot_host, api_version):
    import requests
    import json
    import urllib.parse
    accounts = {}
    api_method = "GET"
    api_url = "/api/%s/accounts" % (api_version)

    response = requests.request(
        api_method,
        urllib.parse.urljoin(turbot_host, api_url),
        auth=(turbot_api_access_key, turbot_api_secret_key),
        verify=turbot_host_certificate_verification,
        headers={
            'content-type': "application/json",
            'cache-control': "no-cache"
        }
    )

    # Convert the response JSON into a Python object
    responseObj = json.loads(response.text)

    for obj in responseObj['items']:
        accounts[obj['id']] = obj['title']

    return accounts