requests.Request

Here are the examples of the python api requests.Request taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

199 Examples 7

Example 1

Project: beckett
Source File: clients.py
View license
    def prepare_http_request(self, method_type, params, **kwargs):
        """
        Prepares the HTTP REQUEST and returns it.

        Args:
            method_type: The HTTP method type
            params: Additional parameters for the HTTP request.
            kwargs: Any extra keyword arguements passed into a client method.

        returns:
            prepared_request: An HTTP request object.
        """
        prepared_request = self.session.prepare_request(
            requests.Request(method=method_type, **params)
        )
        return prepared_request

Example 2

Project: flex
Source File: http.py
View license
def _normalize_requests_request(request):
    import requests

    if not isinstance(request, (requests.Request, requests.PreparedRequest)):
        raise TypeError("Cannot normalize this request object")

    url = request.url
    method = request.method.lower()
    content_type = request.headers.get('Content-Type')
    body = request.body

    return Request(
        url=url,
        body=body,
        method=method,
        content_type=content_type,
        request=request,
    )

Example 3

Project: planet-client-python
Source File: dispatch.py
View license
    def dispatch_request(self, method, url, auth=None, params=None, data=None):
        headers = {}
        content_type = 'application/json'
        if auth:
            headers.update({
                'Authorization': 'api-key %s' % auth.value,
                'content-Type': content_type
            })
        req = Request(method, url, params=params, data=data, headers=headers)
        return self.session.send(req.prepare())

Example 4

View license
    def test_force_preemptive(self):
        with patch.multiple(kerberos_module_name,
                            authGSSClientInit=clientInit_complete,
                            authGSSClientResponse=clientResponse,
                            authGSSClientStep=clientStep_continue):
            auth = requests_kerberos.HTTPKerberosAuth(force_preemptive=True)

            request = requests.Request(url="http://www.example.org")

            auth.__call__(request)

            self.assertTrue('Authorization' in request.headers)
            self.assertEqual(request.headers.get('Authorization'), 'Negotiate GSSRESPONSE')

Example 5

View license
    def test_no_force_preemptive(self):
        with patch.multiple(kerberos_module_name,
                            authGSSClientInit=clientInit_complete,
                            authGSSClientResponse=clientResponse,
                            authGSSClientStep=clientStep_continue):
            auth = requests_kerberos.HTTPKerberosAuth()

            request = requests.Request(url="http://www.example.org")

            auth.__call__(request)

            self.assertTrue('Authorization' not in request.headers)

Example 6

Project: AlexaPi
Source File: auth_web.py
View license
	def index(self):
		scope="alexa_all"
		sd = json.dumps({
		    "alexa:all": {
		        "productID": ProductID,
		        "productInstanceAttributes": {
		            "deviceSerialNumber": "001"
		        }
		    }
		})
		url = "https://www.amazon.com/ap/oa"
		callback = cherrypy.url()  + "code" 
		payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
		req = requests.Request('GET', url, params=payload)
		p = req.prepare()
		raise cherrypy.HTTPRedirect(p.url)

Example 7

Project: tinys3
Source File: test_auth.py
View license
    def test_object_get(self):
        mock_request = Request(method='GET',
                               url="http://johnsmith.s3.amazonaws.com/photos/puppy.jpg",
                               headers={'Date': 'Tue, 27 Mar 2007 19:36:42 +0000'})

        # Call auth
        self.auth(mock_request)

        # test authorization code
        self.assertEquals(mock_request.headers['Authorization'],
                          'AWS AKIAIOSFODNN7EXAMPLE:bWq2s1WEIj+Ydj0vQ697zp+IXMU=')

Example 8

Project: tinys3
Source File: test_auth.py
View license
    def test_object_put(self):
        mock_request = Request(method='PUT',
                               url="http://johnsmith.s3.amazonaws.com/photos/puppy.jpg",
                               headers={'Date': 'Tue, 27 Mar 2007 21:15:45 +0000',
                                        'Content-Type': 'image/jpeg',
                                        'Content-Length': 94328})

        # Call auth
        self.auth(mock_request)

        # test authorization code
        self.assertEquals(mock_request.headers['Authorization'],
                          'AWS AKIAIOSFODNN7EXAMPLE:MyyxeRY7whkBe+bq8fHCL/2kKUg=')

Example 9

Project: tinys3
Source File: test_auth.py
View license
    def test_list_reqeust(self):
        mock_request = Request(method='GET',
                               url="http://johnsmith.s3.amazonaws.com/?prefix=photos&max-keys=50&marker=puppy",
                               headers={'Date': 'Tue, 27 Mar 2007 19:42:41 +0000'})

        # Call auth
        self.auth(mock_request)

        # test authorization code
        self.assertEquals(mock_request.headers['Authorization'],
                          'AWS AKIAIOSFODNN7EXAMPLE:htDYFYduRNen8P9ZfE/s9SuKy0U=')

Example 10

Project: tinys3
Source File: test_auth.py
View license
    def test_fetch(self):
        mock_request = Request(method='GET',
                               url="http://johnsmith.s3.amazonaws.com/?acl",
                               headers={'Date': 'Tue, 27 Mar 2007 19:44:46 +0000'})

        # Call auth
        self.auth(mock_request)

        # test authorization code
        self.assertEquals(mock_request.headers['Authorization'],
                          'AWS AKIAIOSFODNN7EXAMPLE:c2WLPFtWHVgbEmeEG93a4cG37dM=')

Example 11

Project: tinys3
Source File: test_auth.py
View license
    def test_x_amz_date(self):
        mock_request = Request(method='DELETE',
                               url="http://s3.amazonaws.com/johnsmith/photos/puppy.jpg",
                               headers={'Date': 'Tue, 27 Mar 2007 21:20:27 +0000',
                                        'x-amz-date': 'Tue, 27 Mar 2007 21:20:26 +0000'})

        target = """
DELETE



x-amz-date:Tue, 27 Mar 2007 21:20:26 +0000
/johnsmith/photos/puppy.jpg
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 12

Project: tinys3
Source File: test_auth.py
View license
    def test_upload_0_length_file(self):
        """
        Make sure the auth adds content-length: 0 if we don't have any content length defined (for put requests)
        """

        mock_request = Request(method='PUT',
                               url="http://static.johnsmith.net:8080/db-backup.dat.gz",
                               headers={'Date': 'Tue, 27 Mar 2007 21:06:08 +0000',
                                        'x-amz-acl': 'public-read',
                                        'Content-type': 'application/x-download'})
        # Call auth
        self.auth(mock_request)

        # test Content-Length
        self.assertEquals(mock_request.headers['Content-Length'], '0')

Example 13

Project: tinys3
Source File: test_auth.py
View license
    def test_list_all_buckets(self):
        mock_request = Request(method='GET',
                               url="http://s3.amazonaws.com",
                               headers={'Date': 'Wed, 28 Mar 2007 01:29:59 +0000'})

        # Call auth
        self.auth(mock_request)

        # test authorization code
        self.assertEquals(mock_request.headers['Authorization'],
                          'AWS AKIAIOSFODNN7EXAMPLE:qGdzdERIC03wnaRNKh6OqZehG9s=')

Example 14

Project: tinys3
Source File: test_auth.py
View license
    def test_unicode_keys(self):
        mock_request = Request(method='GET',
                               url="http://s3.amazonaws.com/dictionary/fran%C3%A7ais/pr%c3%a9f%c3%a8re",
                               headers={'Date': 'Wed, 28 Mar 2007 01:49:49 +0000'})

        # Call auth
        self.auth(mock_request)

        # test authorization code
        self.assertEquals(mock_request.headers['Authorization'],
                          'AWS AKIAIOSFODNN7EXAMPLE:DNEZGsoieTZ92F3bUfSPQcbGmlM=')

Example 15

Project: tinys3
Source File: test_auth.py
View license
    def test_simple_signature(self):
        self.auth = S3Auth('AKID', 'secret')
        mock_request = Request(method='POST', url='/', headers={'Date': 'DATE-STRING'})

        flexmock(self.auth).should_receive('string_to_sign').and_return('string-to-sign')

        self.auth(mock_request)

        self.assertEquals(mock_request.headers['Authorization'], 'AWS AKID:Gg5WLabTOvH0WMd15wv7lWe4zK0=')

Example 16

Project: tinys3
Source File: test_auth.py
View license
    def test_string_to_sign(self):
        mock_request = Request(method='POST', url='/', headers={'Date': 'DATE-STRING'})

        target = """
POST


DATE-STRING
/
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 17

Project: tinys3
Source File: test_auth.py
View license
    def test_sts_includes_content_md5_and_content_type(self):
        mock_request = Request(method='POST', url='/',
                               headers={'Date': 'DATE-STRING',
                                        'Content-Type': 'CONTENT-TYPE',
                                        'Content-MD5': 'CONTENT-MD5'})

        target = """
POST
CONTENT-MD5
CONTENT-TYPE
DATE-STRING
/
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 18

Project: tinys3
Source File: test_auth.py
View license
    def test_sts_includes_the_http_method(self):
        mock_request = Request(method='VERB', url='/',
                               headers={'Date': 'DATE-STRING'})

        target = """
VERB


DATE-STRING
/
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 19

Project: tinys3
Source File: test_auth.py
View license
    def test_sts_includes_any_x_amz_headers_but_not_others(self):
        mock_request = Request(method='POST', url='/',
                               headers={'Date': 'DATE-STRING',
                                        'X-Amz-Abc': 'abc',
                                        'X-Amz-Xyz': 'xyz',
                                        'random-header': 'random'})

        target = """
POST


DATE-STRING
x-amz-abc:abc
x-amz-xyz:xyz
/
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 20

Project: tinys3
Source File: test_auth.py
View license
    def test_sts_includes_x_amz_headers_that_are_lower_cased(self):
        mock_request = Request(method='POST', url='/',
                               headers={'Date': 'DATE-STRING',
                                        'x-amz-Abc': 'abc',
                                        'x-amz-Xyz': 'xyz',
                                        'random-header': 'random'})

        target = """
POST


DATE-STRING
x-amz-abc:abc
x-amz-xyz:xyz
/
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 21

Project: tinys3
Source File: test_auth.py
View license
    def test_sts_includes_sub_resource_value_when_present(self):
        mock_request = Request(method='POST', url='/bucket_name/key?versionId=123',
                               headers={'Date': 'DATE-STRING'})

        target = """
POST


DATE-STRING
/bucket_name/key?versionId=123
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 22

Project: tinys3
Source File: test_auth.py
View license
    def test_sts_omits_non_sub_resource_querystring_params_from_the_resource_string(self):
        mock_request = Request(method='POST', url='/?versionId=abc&next-marker=xyz',
                               headers={'Date': 'DATE-STRING'})

        target = """
POST


DATE-STRING
/?versionId=abc
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 23

Project: tinys3
Source File: test_auth.py
View license
    def test_sts_includes_the_un_decoded_query_string_param_for_sub_resources(self):
        mock_request = Request(method='POST', url='/?versionId=a%2Bb',
                               headers={'Date': 'DATE-STRING'})

        target = """
POST


DATE-STRING
/?versionId=a%2Bb
""".strip()

        self.assertEquals(self.auth.string_to_sign(mock_request), target)

Example 24

Project: solvebio-python
Source File: client.py
View license
    def _log_raw_request(self, method, url, **kwargs):
        from requests import Request, Session
        req = Request(method=method.upper(), url=url,
                      data=kwargs['data'], params=kwargs['params'])
        prepped = Session().prepare_request(req, )
        logger.debug(prepped.headers)
        logger.debug(prepped.body)

Example 25

Project: streamlink
Source File: http.py
View license
    def __json__(self):
        method = self.args.get("method", "GET")
        req = requests.Request(method=method, **valid_args(self.args))

        # prepare_request is only available in requests 2.0+
        if hasattr(self.session.http, "prepare_request"):
            req = self.session.http.prepare_request(req)
        else:
            req = req.prepare()

        headers = dict(map(normalize_key, req.headers.items()))

        return dict(type=type(self).shortname(), url=req.url,
                    method=req.method, headers=headers,
                    body=req.body)

Example 26

Project: traktforalfred
Source File: request.py
View license
    def prepare(self):
        self.request = Request()

        self.transform_parameters()
        self.request.url = self.construct_url()

        self.request.method = self.transform_method()
        self.request.headers = self.transform_headers()

        data = self.transform_data()

        if data:
            self.request.data = json.dumps(data)

        return self.request.prepare()

Example 27

View license
    def _fetchHtml(self, insecure):
        query_string = {
                's': self.current_q,
                't': self.type[0],
                'm': 'ALL',
                'r': '',
                'b': str(self.current_q_item_offset)
            }

        protocol = 'http' if insecure else 'https'
        user_agent = {'User-agent': 'yahoo-ticker-symbol-downloader'}
        req = requests.Request('GET', protocol+'://finance.yahoo.com/lookup/',
                headers=user_agent, params=query_string)
        req = req.prepare()
        print("req " + req.url) # Used for debugging
        resp = self.rsession.send(req)
        resp.raise_for_status()

        return resp.text

Example 28

Project: rinse
Source File: message.py
View license
    def request(self, url=None, action=None):
        """Generate a requests.Request instance."""
        headers = self.http_headers.copy()
        if action is not None:
            headers['SOAPAction'] = action
        return requests.Request(
            'POST',
            url or self.url,
            data=self.tostring(pretty_print=True, encoding='utf-8'),
            headers=headers,
        )

Example 29

Project: ttrss-python
Source File: auth.py
View license
    def response_hook(self, r, **kwargs):
        j = json.loads(r.text)
        if int(j['status']) == 0:
            return r

        self.sid = self._get_sid(r.request.url)

        r.request.deregister_hook('response', self.response_hook)
        j = json.loads(r.request.body)
        j.update({'sid': self.sid})
        req = requests.Request('POST', r.request.url, auth=self.http_auth)
        req.data = json.dumps(j)
        _r = requests.Session().send(req.prepare())
        raise_on_error(_r)

        return _r

Example 30

Project: ttrss-python
Source File: auth.py
View license
    def __call__(self, r):
        r.register_hook('response', self.response_hook)
            
        data = json.loads(r.body)
        if 'sid' not in data:
            if self.sid is None:
                self.sid = self._get_sid(r.url)
            data.update({'sid': self.sid})
            req = requests.Request('POST', r.url, auth=self.http_auth)
            req.data = json.dumps(data)
            return req.prepare()
        else:
            self.sid = data['sid']
        return r

Example 31

Project: linkchecker
Source File: httpurl.py
View license
    def build_request(self):
        """Build a prepared request object."""
        clientheaders = {}
        if (self.parent_url and
            self.parent_url.lower().startswith(HTTP_SCHEMAS)):
            clientheaders["Referer"] = self.parent_url
        kwargs = dict(
            method='GET',
            url=self.url,
            headers=clientheaders,
        )
        if self.auth:
            kwargs['auth'] = self.auth
        log.debug(LOG_CHECK, "Prepare request with %s", kwargs)
        request = requests.Request(**kwargs)
        return self.session.prepare_request(request)

Example 32

Project: xively-python
Source File: tests.py
View license
    def test_api_key_header(self):
        """Tests the X-ApiKey header is set on requests using KeyAuth."""
        request = requests.Request()
        auth = xively.client.KeyAuth("ABCDE")
        auth(request)
        self.assertEqual(request.headers['X-ApiKey'], "ABCDE")

Example 33

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_basic_building(self):
        req = requests.Request()
        req.url = 'http://kennethreitz.org/'
        req.data = {'life': '42'}

        pr = req.prepare()
        assert pr.url == req.url
        assert pr.body == 'life=42'

Example 34

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_HTTP_200_OK_GET_ALTERNATIVE(self):
        r = requests.Request('GET', httpbin('get'))
        s = requests.Session()
        s.proxies = getproxies()

        r = s.send(r.prepare())

        assert r.status_code == 200

Example 35

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    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})

Example 36

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_prepared_request_hook(self):
        def hook(resp, **kwargs):
            resp.hook_working = True
            return resp

        req = requests.Request('GET', HTTPBIN, hooks={'response': hook})
        prep = req.prepare()

        s = requests.Session()
        s.proxies = getproxies()
        resp = s.send(prep)

        assert hasattr(resp, 'hook_working')

Example 37

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_session_pickling(self):
        r = requests.Request('GET', httpbin('get'))
        s = requests.Session()

        s = pickle.loads(pickle.dumps(s))
        s.proxies = getproxies()

        r = s.send(r.prepare())
        assert r.status_code == 200

Example 38

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_header_keys_are_native(self):
        headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}
        r = requests.Request('GET', httpbin('get'), headers=headers)
        p = r.prepare()

        # This is testing that they are builtin strings. A bit weird, but there
        # we go.
        assert 'unicode' in p.headers.keys()
        assert 'byte' in p.headers.keys()

Example 39

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_can_send_nonstring_objects_with_files(self):
        data = {'a': 0.0}
        files = {'b': 'foo'}
        r = requests.Request('POST', httpbin('post'), data=data, files=files)
        p = r.prepare()

        assert 'multipart/form-data' in p.headers['Content-Type']

Example 40

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_autoset_header_values_are_native(self):
        data = 'this is a string'
        length = '16'
        req = requests.Request('POST', httpbin('post'), data=data)
        p = req.prepare()

        assert p.headers['Content-Length'] == length

Example 41

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_oddball_schemes_dont_check_URLs(self):
        test_urls = (
            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',
            'file:///etc/passwd',
            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',
        )
        for test_url in test_urls:
            req = requests.Request('GET', test_url)
            preq = req.prepare()
            assert test_url == preq.url

Example 42

Project: yandex-tank
Source File: client.py
View license
    def get_raw(self, addr):
        if not self.address:
            raise ValueError("Can't request unknown address")

        addr = self.address + addr
        logger.debug("Making request to: %s", addr)
        req = requests.Request('GET', addr)
        prepared = self.session.prepare_request(req)
        resp = self.session.send(prepared, timeout=self.api_timeout)
        resp.raise_for_status()
        resp_data = resp.content.strip()
        logger.debug("Raw response: %s", resp_data)
        return resp_data

Example 43

Project: yandex-tank
Source File: client.py
View license
    def post_raw(self, addr, txt_data):
        if not self.address:
            raise ValueError("Can't request unknown address")

        addr = self.address + addr
        logger.debug("Making POST request to: %s", addr)
        req = requests.Request("POST", addr, data=txt_data)
        prepared = self.session.prepare_request(req)
        resp = self.session.send(prepared, timeout=self.api_timeout)
        resp.raise_for_status()
        logger.debug("Response: %s", resp.content)
        return resp.content

Example 44

Project: yandex-tank
Source File: client.py
View license
    def post(self, addr, data):
        addr = self.address + addr
        json_data = json.dumps(data, indent=2)
        logger.debug("Making POST request to: %s\n%s", addr, json_data)
        req = requests.Request("POST", addr, data=json_data)
        prepared = self.session.prepare_request(req)
        resp = self.session.send(prepared, timeout=self.api_timeout)
        resp.raise_for_status()
        logger.debug("Response: %s", resp.content)
        return resp.json()

Example 45

Project: bravado
Source File: http_client_test.py
View license
@pytest.fixture
def mock_request():
    return mock.create_autospec(
        requests.Request,
        method='GET',
        url='http://example.com',
        params={})

Example 46

Project: paasta
Source File: test_mesos_tools.py
View license
@mock.patch('requests.get', autospec=True)
@mock.patch('socket.getfqdn', autospec=True)
def test_get_local_slave_state_connection_error(
    mock_getfqdn,
    mock_requests_get,
):
    fake_request = requests.Request('GET', url='doesnt_matter')
    mock_getfqdn.return_value = 'fake_hostname'
    mock_requests_get.side_effect = requests.ConnectionError(
        'fake_message',
        request=fake_request,
    )

    with raises(mesos_tools.MesosSlaveConnectionError):
        mesos_tools.get_local_slave_state()

Example 47

Project: wharf
Source File: client.py
View license
    def _attach_websocket(self, container, params=None):
        if six.PY3:
            raise NotImplementedError("This method is not currently supported "
                                      "under python 3")
        url = self._url("/containers/{0}/attach/ws".format(container))
        req = requests.Request("POST", url, params=self._attach_params(params))
        full_url = req.prepare().url
        full_url = full_url.replace("http://", "ws://", 1)
        full_url = full_url.replace("https://", "wss://", 1)
        return self._create_websocket_connection(full_url)

Example 48

Project: livestreamer
Source File: http.py
View license
    def __json__(self):
        method = self.args.get("method", "GET")
        req = requests.Request(method=method, **valid_args(self.args))

        # prepare_request is only available in requests 2.0+
        if hasattr(self.session.http, "prepare_request"):
            req = self.session.http.prepare_request(req)
        else:
            req = req.prepare()

        headers = dict(map(normalize_key, req.headers.items()))

        return dict(type=type(self).shortname(), url=req.url,
                    method=req.method, headers=headers,
                    body=req.body)

Example 49

Project: django-log-request-id
Source File: tests.py
View license
    def test_request_id_passthrough_with_custom_header(self):
        with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER', OUTGOING_REQUEST_ID_HEADER='OUTGOING_REQUEST_ID_HEADER'):
            from log_request_id.session import Session
            request = self.factory.get('/')
            request.META['REQUEST_ID_HEADER'] = 'some_request_id'
            middleware = RequestIDMiddleware()
            middleware.process_request(request)
            self.assertEqual(request.id, 'some_request_id')
            session = Session()
            outgoing = Request('get', 'http://nowhere')
            session.prepare_request(outgoing)
            self.assertEqual(
                outgoing.headers['OUTGOING_REQUEST_ID_HEADER'],
                'some_request_id'
            )

Example 50

Project: django-log-request-id
Source File: tests.py
View license
    def test_request_id_passthrough(self):
        with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
            from log_request_id.session import Session
            request = self.factory.get('/')
            request.META['REQUEST_ID_HEADER'] = 'some_request_id'
            middleware = RequestIDMiddleware()
            middleware.process_request(request)
            self.assertEqual(request.id, 'some_request_id')
            session = Session()
            outgoing = Request('get', 'http://nowhere')
            session.prepare_request(outgoing)
            self.assertEqual(
                outgoing.headers['REQUEST_ID_HEADER'],
                'some_request_id'
            )