How to use the requests.Request function in requests

To help you get started, we’ve selected a few requests examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lemon24 / reader / tests / test_parser.py View on Github external
def do_nothing_plugin(session, response, request):
        do_nothing_plugin.called = True
        assert isinstance(session, requests.Session)
        assert isinstance(response, requests.Response)
        assert isinstance(request, requests.Request)
        assert request.url == feed_url
        return None
github logzio / logzio-es2graphite / logzio-es2graphite / packages / requests-2.5.1 / test_requests.py View on Github external
def test_hook_receives_request_arguments(self):
        def hook(resp, **kwargs):
            assert resp is not None
            assert kwargs != {}

        requests.Request('GET', HTTPBIN, hooks={'response': hook})
github vivekseth / generic_oauth / generic_oauth / __init__.py View on Github external
def authorization_url(self):
        url = 'https://accounts.spotify.com/authorize'
        data = {
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'scope': self.scope,
            'state': self.state,
            'response_type': 'code'
        }
        req = requests.Request('GET', url, data=data)
        prepped = req.prepare()
        
        return prepped.url + '?' + prepped.body
github boto / requestbuilder / requestbuilder / service.py View on Github external
def __log_and_prepare_request(self, method, url, params, data, files,
                                  headers, auth):
        hooks = {'response': functools.partial(_log_response_data, self.log)}
        if auth:
            bound_auth = auth.bind_to_service(self)
        else:
            bound_auth = None
        request = requests.Request(method=method, url=url, params=params,
                                   data=data, files=files, headers=headers,
                                   auth=bound_auth)
        p_request = self.session.prepare_request(request)
        p_request.hooks = {'response': hooks['response']}
        self.log.debug('request  method: %s', request.method)
        self.log.debug('request  url:    %s', p_request.url)
        if isinstance(p_request.headers, (dict, collections.Mapping)):
            for key, val in sorted(p_request.headers.iteritems()):
                if key.lower().endswith('password'):
                    val = ''
                self.log.debug('request  header: %s: %s', key, val)
        if isinstance(request.params, (dict, collections.Mapping)):
            for key, val in sorted(urlparse.parse_qsl(
                    urlparse.urlparse(p_request.url).query,
                    keep_blank_values=True)):
                if key.lower().endswith('password'):
github yandex / yandex-tank / yandextank / plugins / DataUploader / client.py View on Github external
def __make_writer_request(
            self,
            params=None,
            json=None,
            http_method="POST",
            trace=False):
        '''
        Send request to writer service.
        '''
        request = requests.Request(
            http_method,
            self.writer_url,
            params=params,
            json=json,
            headers={
                'User-Agent': self.user_agent})
        ids = id_gen(str(uuid.uuid4()))
        network_timeouts = self.network_timeouts()
        maintenance_timeouts = self.maintenance_timeouts()
        while True:
            try:
                response = self.__send_single_request(request, ids.next(), trace=trace)
                return response
            except (Timeout, ConnectionError, ProtocolError):
                logger.warn(traceback.format_exc())
                try:
github KartikTalwar / Duolingo / duolingo.py View on Github external
def _make_req(self, url, data=None):
        headers = {}
        if self.jwt is not None:
            headers['Authorization'] = 'Bearer ' + self.jwt
        req = requests.Request('POST' if data else 'GET',
                               url,
                               json=data,
                               headers=headers,
                               cookies=self.session.cookies)
        prepped = req.prepare()
        return self.session.send(prepped)
github ceph / teuthology / teuthology / provision / pelagos.py View on Github external
def do_request(self, url_suffix, url="" , data=None, method='GET', verify=True):
        """
        A convenience method to submit a request to the Pelagos server
        :param url_suffix: The portion of the URL to append to the endpoint,
                           e.g.  '/system/info'
        :param data: Optional JSON data to submit with the request
        :param method: The HTTP method to use for the request (default: 'GET')
        :param verify: Whether or not to raise an exception if the request is
                       unsuccessful (default: True)
        :returns: A requests.models.Response object
        """
        prepared_url = url or config.pelagos['endpoint'] + url_suffix
        self.log.debug("Sending %s request to: '%s'", method, prepared_url)
        if data:
            self.log.debug("Using data: '%s'", str(data))
        req = requests.Request(
            method,
            prepared_url,
            data=data
        )
        prepared = req.prepare()
        resp = requests.Session().send(prepared)
        if not resp.ok and resp.text:
            self.log.error("Returned status code: '%s', text: %s",
                           resp.status_code, resp.text or 'Empty')
        if verify:
            resp.raise_for_status()
        return resp
github quay / quay / util / config / provider / k8sprovider.py View on Github external
def _execute_k8s_api(self, method, relative_url, data=None):
        headers = {"Authorization": "Bearer " + self._service_token}

        if data:
            headers["Content-Type"] = "application/json"

        data = json.dumps(data) if data else None
        session = Session()
        url = "https://%s/api/v1/%s" % (self._api_host, relative_url)

        request = Request(method, url, data=data, headers=headers)
        return session.send(request.prepare(), verify=False, timeout=2)
github NDAR / nda-tools / nda-validationtool-client.py View on Github external
)

    headers = {'accept': 'application/json'}
    if api.__class__.__name__ == 'ValidationTask':
        auth = None
        headers.update({'content-type': 'text/csv'})
    else:
        auth = requests.auth.HTTPBasicAuth(api.config.username, api.config.password)
        headers.update({'content-type': 'application/json'})
    if not session:
        session = requests.session()
        session.mount(endpoint, HTTPAdapter(max_retries=retry))
    r = None
    response = None
    try:
        r = session.send(requests.Request(verb, endpoint, headers, auth=auth, data=data).prepare(),
                         timeout=300, stream=False)
    except requests.exceptions.RequestException as e:
        print('\nAn error occurred while making {} request, check your endpoint configuration:\n'.
              format(e.request.method))
        print(e)
        if api.__class__.__name__.endswith('Task'):
            api.shutdown_flag.set()
            thread.interrupt_main()
        exit_client(signal.SIGINT)

    if r and r.ok:
        try:
            response = json.loads(r.text)
        except ValueError:
            print('Your request returned an unexpected response, please check your endpoints.\n'
                  'Action: {}\n'
github CenturyLinkCloud / clc-python-sdk / src / clc / APIv1 / api.py View on Github external
:returns: decoded API json result
		"""
		if not clc._LOGIN_COOKIE_V1:  API._Login()

		if session is None:
		    session = clc._REQUESTS_SESSION

		session.headers.update({'content-type': 'application/json'})

		r = session.request(method,"%s%s/JSON" % (clc.defaults.ENDPOINT_URL_V1,url),
                             params=payload,
                             cookies=clc._LOGIN_COOKIE_V1,
                             verify=API._ResourcePath('clc/cacert.pem'))

		if debug:
			API._DebugRequest(request=requests.Request(method,"%s%s/JSON" % (clc.defaults.ENDPOINT_URL_V1,url),
                              data=payload,headers=session.headers).prepare(),response=r)

		try:
			if int(r.json()['StatusCode']) == 0:  
				if clc.args and not silent:  clc.v1.output.Status('SUCCESS',2,'%s' % (r.json()['Message']))
				return(r.json())
			elif int(r.json()['StatusCode']) in hide_errors:
				return(r.json())
			elif int(r.json()['StatusCode']) == 2:  
				# Account is deleted
				#raise clc.v1.Account.eletedException(r.json()['Message'])
				if clc.args and not silent:  clc.v1.output.Status('ERROR',3,'%s' % (r.json()['Message']))
				raise Exception(r.json()['Message'])
			elif int(r.json()['StatusCode']) == 5:  
				# Account or datacenter does not exist
				raise clc.v1.AccountDoesNotExistException(r.json()['Message'])