Python requests.Response() Examples

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

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

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

Example 1
Project: drydock   Author: airshipit   File: promenade_client.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, route, query=None, timeout=None):
        """
        Send a GET request to Promenade.

        :param string route: The URL string following the hostname and API prefix
        :param dict query: A dict of k, v pairs to add to the query string
        :param timeout: A single or tuple value for connect, read timeout.
            A single value indicates the read timeout only
        :return: A requests.Response object
        """
        auth_refresh = False
        while True:
            url = self.base_url + route
            self.logger.debug('GET ' + url)
            self.logger.debug('Query Params: ' + str(query))
            resp = self.__session.get(
                url, params=query, timeout=self._timeout(timeout))

            if resp.status_code == 401 and not auth_refresh:
                self.set_auth()
                auth_refresh = True
            else:
                break

        return resp 
Example 2
Project: drydock   Author: airshipit   File: session.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, endpoint, query=None, timeout=None):
        """
        Send a GET request to Drydock.

        :param string endpoint: The URL string following the hostname and API prefix
        :param dict query: A dict of k, v pairs to add to the query string
        :param timeout: A single or tuple value for connect, read timeout.
            A single value indicates the read timeout only
        :return: A requests.Response object
        """
        auth_refresh = False
        while True:
            url = self.base_url + endpoint
            self.logger.debug('GET ' + url)
            self.logger.debug('Query Params: ' + str(query))
            resp = self.__session.get(
                url, params=query, timeout=self._timeout(timeout))

            if resp.status_code == 401 and not auth_refresh:
                self.set_auth()
                auth_refresh = True
            else:
                break

        return resp 
Example 3
Project: django-payfast   Author: PiDelport   File: test_integration_sandbox.py    License: MIT License 6 votes vote down vote up
def post_sandbox_payment(
        session_type,  # type: str
        session_id,  # type: str
        selected_method,  # type: str
):  # type: (...) -> requests.Response
    """
    Post a PayFast sandbox wallet payment confirmation.

    The parameters should come from the checkout page.
    """
    # This call is referenced from:
    # https://sandbox.payfast.co.za/js/engine_v2.js?version=5.2.6
    # (See the #pay-with-wallet click handler.)
    url = sandbox_process_url + '/payment_method?{}={}'.format(session_type, session_id)
    response = requests.post(url, {'selected_method': selected_method})
    response.raise_for_status()
    return response 
Example 4
Project: jupyterlab_code_formatter   Author: ryantam626   File: test_handlers.py    License: MIT License 6 votes vote down vote up
def _format_code_request(
        self,
        formatter: str,
        code: t.List[str],
        options: t.Dict[str, t.Any],
        plugin_version: t.Optional[str] = None,
    ) -> requests.Response:
        return self.request(
            verb="POST",
            path="/jupyterlab_code_formatter/format",
            data=json.dumps(
                {
                    "code": code,
                    "options": options,
                    "notebook": True,
                    "formatter": formatter,
                }
            ),
            headers=self._create_headers(plugin_version),
        ) 
Example 5
Project: botbuilder-python   Author: microsoft   File: direct_line_client.py    License: MIT License 6 votes vote down vote up
def send_message(self, text: str, retry_count: int = 3) -> Response:
        """Send raw text to bot framework using direct line api"""

        url = "/".join(
            [self._base_url, "conversations", self._conversation_id, "activities"]
        )
        json_payload = {
            "conversationId": self._conversation_id,
            "type": "message",
            "from": {"id": "user1"},
            "text": text,
        }

        success = False
        current_retry = 0
        bot_response = None
        while not success and current_retry < retry_count:
            bot_response = requests.post(url, headers=self._headers, json=json_payload)
            current_retry += 1
            if bot_response.status_code == 200:
                success = True

        return bot_response 
Example 6
Project: zun   Author: openstack   File: fake_requests.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, status_code, content=None, headers=None):
        """A requests.Response that can be used as a mock return_value.

        A key feature is that the instance will evaluate to True or False like
        a real Response, based on the status_code.

        Properties like ok, status_code, text, and content, and methods like
        json(), work as expected based on the inputs.

        :param status_code: Integer HTTP response code (200, 404, etc.)
        :param content: String supplying the payload content of the response.
                        Using a json-encoded string will make the json() method
                        behave as expected.
        :param headers: Dict of HTTP header values to set.
        """
        super(FakeResponse, self).__init__()
        self.status_code = status_code
        if content:
            self._content = content.encode('utf-8')
            self.encoding = 'utf-8'
        if headers:
            self.headers = headers 
Example 7
Project: rets   Author: opendoor-labs   File: client.py    License: MIT License 6 votes vote down vote up
def _get_metadata(self, type_: str, metadata_id: str = '0') -> Response:
        """
        :param type_: The type of metadata being requested. The Type MUST begin with METADATA and
            may be one of the defined metadata types (see Section 11).

        :param metadata_id: If the last metadata_id is 0 (zero), then the request is for all Type
            metadata contained within that level; if the last metadata_id is '*', then the request
            is for all Type metadata contained within that level and all metadata Types contained
            within the requested Type. This means that for a metadata-id of METADATA-SYSTEM, for
            example, the server is expected to return all metadata.

            Note: The metadata_id for METADATA-SYSTEM and METADATA-RESOURCE must be 0 or *.
        """
        payload = {
            'Type': 'METADATA-' + type_.upper(),
            'ID': metadata_id,
            'Format': 'COMPACT',
        }
        return self._http_request(self._url_for('GetMetadata'), payload=payload) 
Example 8
Project: rets   Author: opendoor-labs   File: client.py    License: MIT License 6 votes vote down vote up
def _http_request(self, url: str, headers: dict = None, payload: dict = None) -> Response:
        if not self._session:
            raise RetsClientError('Session not instantiated. Call .login() first')

        request_headers = {
            **(headers or {}),
            'User-Agent': self.user_agent,
            'RETS-Version': self.rets_version,
            'RETS-UA-Authorization': self._rets_ua_authorization()
        }

        if self._use_get_method:
            if payload:
                url = '%s?%s' % (url, urlencode(payload))
            response = self._session.get(url, auth=self._http_auth, headers=request_headers)
        else:
            response = self._session.post(url, auth=self._http_auth, headers=request_headers, data=payload)

        response.raise_for_status()
        self._rets_session_id = self._session.cookies.get('RETS-Session-ID', '')
        return response 
Example 9
Project: rets   Author: opendoor-labs   File: parse_object.py    License: MIT License 6 votes vote down vote up
def parse_object(response: Response) -> Sequence[Object]:
    """
    Parse the response from a GetObject transaction. If there are multiple
    objects to be returned then the response should be a multipart response.
    The headers of the response (or each part in the multipart response)
    contains the metadata for the object, including the location if requested.
    The body of the response should contain the binary content of the object,
    an XML document specifying a transaction status code, or left empty.
    """
    content_type = response.headers.get('content-type')

    if content_type and 'multipart/parallel' in content_type:
        return _parse_multipart(response)

    object_ = _parse_body_part(response)
    return (object_,) if object_ is not None else () 
Example 10
Project: rets   Author: opendoor-labs   File: parse.py    License: MIT License 6 votes vote down vote up
def parse_system(response: Response) -> SystemMetadata:
    """
    Parse the server system information from a SYSTEM GetMetadata transaction.

    <RETS ReplyCode="0" ReplyText="Success">
        <METADATA-SYSTEM Date="2016-11-24T05:24:06Z" Version="01.09.02991">
            <SYSTEM SystemDescription="ARMLS" SystemID="az" TimeZoneOffset="-06:00"/>
            <COMMENTS/>
        </METADATA-SYSTEM>
    </RETS>
    """
    elem = parse_xml(response)
    metadata_system_elem = _find_or_raise(elem, 'METADATA-SYSTEM')
    system_elem = _find_or_raise(metadata_system_elem, 'SYSTEM')
    comments_elem = metadata_system_elem.find('COMMENTS')
    return SystemMetadata(
        system_id=system_elem.get('SystemID'),
        system_description=system_elem.get('SystemDescription'),
        system_date=metadata_system_elem.get('Date'),
        system_version=metadata_system_elem.get('Version'),

        # Optional fields
        time_zone_offset=system_elem.get('TimeZoneOffset'),
        comments=comments_elem and (comments_elem.text or None),
    ) 
Example 11
Project: rets   Author: opendoor-labs   File: parse.py    License: MIT License 6 votes vote down vote up
def parse_search(response: Response) -> SearchResult:
    try:
        elem = parse_xml(response)
    except RetsApiError as e:
        if e.reply_code == 20201:  # No records found
            return SearchResult(0, False, ())
        raise

    count_elem = elem.find('COUNT')
    if count_elem is not None:
        count = int(count_elem.get('Records'))
    else:
        count = None

    try:
        data = tuple(_parse_data(elem))
    except RetsParseError:
        data = None

    return SearchResult(
        count=count,
        # python xml.etree.ElementTree.Element objects are always considered false-y
        max_rows=elem.find('MAXROWS') is not None,
        data=data,
    ) 
Example 12
Project: tekore   Author: felix-hilden   File: extending.py    License: MIT License 6 votes vote down vote up
def send(self, request: Request) -> Response:
        """Delegate request to underlying sender and retry if failed."""
        if self.is_async:
            return self._async_send(request)

        tries = self.retries + 1
        delay_seconds = 1

        while tries > 0:
            r = self.sender.send(request)

            if r.status_code == 429:
                seconds = r.headers.get('Retry-After', 1)
                time.sleep(int(seconds) + 1)
            elif r.status_code >= 500 and tries > 1:
                tries -= 1
                time.sleep(delay_seconds)
                delay_seconds *= 2
            else:
                return r 
Example 13
Project: tekore   Author: felix-hilden   File: extending.py    License: MIT License 6 votes vote down vote up
def _async_send(self, request: Request) -> Response:
        tries = self.retries + 1
        delay_seconds = 1

        while tries > 0:
            r = await self.sender.send(request)

            if r.status_code == 429:
                seconds = r.headers.get('Retry-After', 1)
                await asyncio.sleep(int(seconds) + 1)
            elif r.status_code >= 500 and tries > 1:
                tries -= 1
                await asyncio.sleep(delay_seconds)
                delay_seconds *= 2
            else:
                return r 
Example 14
Project: tekore   Author: felix-hilden   File: extending.py    License: MIT License 6 votes vote down vote up
def send(self, request: Request) -> Response:
        """Maybe load request from cache, or delegate to underlying sender."""
        if self.is_async:
            return self._async_send(request)

        if request.method.lower() != 'get':
            return self.sender.send(request)

        cached, etag = self._load(request)
        if cached is not None and etag is None:
            return cached
        elif etag is not None:
            request.headers.update(ETag=etag)

        fresh = self.sender.send(request)
        return self._handle_fresh(request, fresh, cached) 
Example 15
Project: tekore   Author: felix-hilden   File: expiring.py    License: MIT License 6 votes vote down vote up
def handle_errors(response: Response) -> None:
    """Examine response and raise errors accordingly."""
    if response.status_code < 400:
        return

    if response.status_code < 500:
        content = response.json()
        error_str = '{} {}: {}'.format(
            response.status_code,
            content['error'],
            content['error_description']
        )
    else:
        error_str = 'Unexpected error!'

    error_cls = get_error(response.status_code)
    raise error_cls(error_str, response=response) 
Example 16
Project: instaloader   Author: instaloader   File: instaloadercontext.py    License: MIT License 6 votes vote down vote up
def get_raw(self, url: str, _attempt=1) -> requests.Response:
        """Downloads a file anonymously.

        :raises QueryReturnedNotFoundException: When the server responds with a 404.
        :raises QueryReturnedForbiddenException: When the server responds with a 403.
        :raises ConnectionException: When download failed.

        .. versionadded:: 4.2.1"""
        with self.get_anonymous_session() as anonymous_session:
            resp = anonymous_session.get(url, stream=True)
        if resp.status_code == 200:
            resp.raw.decode_content = True
            return resp
        else:
            if resp.status_code == 403:
                # suspected invalid URL signature
                raise QueryReturnedForbiddenException("403 when accessing {}.".format(url))
            if resp.status_code == 404:
                # 404 not worth retrying.
                raise QueryReturnedNotFoundException("404 when accessing {}.".format(url))
            raise ConnectionException("HTTP error code {}.".format(resp.status_code)) 
Example 17
Project: schemathesis   Author: kiwicom   File: models.py    License: MIT License 6 votes vote down vote up
def call(
        self,
        base_url: Optional[str] = None,
        session: Optional[requests.Session] = None,
        headers: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> requests.Response:
        """Make a network call with `requests`."""
        if session is None:
            session = requests.Session()
            close_session = True
        else:
            close_session = False

        data = self.as_requests_kwargs(base_url)
        if headers is not None:
            data["headers"] = {**(data["headers"] or {}), **headers}
        data.update(kwargs)
        response = session.request(**data)  # type: ignore
        if close_session:
            session.close()
        return response 
Example 18
Project: schemathesis   Author: kiwicom   File: models.py    License: MIT License 6 votes vote down vote up
def call_asgi(
        self,
        app: Any = None,
        base_url: Optional[str] = "http://testserver",
        headers: Optional[Dict[str, str]] = None,
        **kwargs: Any,
    ) -> requests.Response:
        application = app or self.app
        if application is None:
            raise RuntimeError(
                "ASGI application instance is required. "
                "Please, set `app` argument in the schema constructor or pass it to `call_asgi`"
            )
        client = ASGIClient(application)

        return self.call(base_url=base_url, session=client, headers=headers, **kwargs) 
Example 19
Project: schemathesis   Author: kiwicom   File: models.py    License: MIT License 6 votes vote down vote up
def from_prepared_request(cls, prepared: requests.PreparedRequest) -> "Request":
        """A prepared request version is already stored in `requests.Response`."""
        body = prepared.body or b""

        if isinstance(body, str):
            # can be a string for `application/x-www-form-urlencoded`
            body = body.encode("utf-8")

        # these values have `str` type at this point
        uri = cast(str, prepared.url)
        method = cast(str, prepared.method)
        return cls(
            uri=uri,
            method=method,
            headers={key: [value] for (key, value) in prepared.headers.items()},
            body=base64.b64encode(body).decode(),
        ) 
Example 20
Project: schemathesis   Author: kiwicom   File: core.py    License: MIT License 6 votes vote down vote up
def _network_test(
    case: Case,
    checks: Iterable[CheckFunction],
    targets: Iterable[Target],
    result: TestResult,
    session: requests.Session,
    timeout: Optional[float],
    store_interactions: bool,
    headers: Optional[Dict[str, Any]],
    feedback: Feedback,
) -> requests.Response:
    # pylint: disable=too-many-arguments
    response = case.call(session=session, headers=headers, timeout=timeout)
    run_targets(targets, response.elapsed.total_seconds())
    if store_interactions:
        result.store_requests_response(response)
    run_checks(case, checks, result, response)
    feedback.add_test_case(case, response)
    return response 
Example 21
Project: drydock   Author: airshipit   File: promenade_client.py    License: Apache License 2.0 5 votes vote down vote up
def put(self, endpoint, query=None, body=None, data=None, timeout=None):
        """
        Send a PUT request to Promenade. If both body and data are specified,
        body will be used.

        :param string endpoint: The URL string following the hostname and API prefix
        :param dict query: A dict of k, v parameters to add to the query string
        :param string body: A string to use as the request body. Will be treated as raw
        :param data: Something json.dumps(s) can serialize. Result will be used as the request body
        :param timeout: A single or tuple value for connect, read timeout.
            A single value indicates the read timeout only
        :return: A requests.Response object
        """
        auth_refresh = False
        url = self.base_url + endpoint
        while True:
            self.logger.debug('PUT ' + url)
            self.logger.debug('Query Params: ' + str(query))
            if body is not None:
                self.logger.debug(
                    "Sending PUT with explicit body: \n%s" % body)
                resp = self.__session.put(
                    self.base_url + endpoint,
                    params=query,
                    data=body,
                    timeout=self._timeout(timeout))
            else:
                self.logger.debug(
                    "Sending PUT with JSON body: \n%s" % str(data))
                resp = self.__session.put(
                    self.base_url + endpoint,
                    params=query,
                    json=data,
                    timeout=self._timeout(timeout))
            if resp.status_code == 401 and not auth_refresh:
                self.set_auth()
                auth_refresh = True
            else:
                break

        return resp 
Example 22
Project: drydock   Author: airshipit   File: promenade_client.py    License: Apache License 2.0 5 votes vote down vote up
def post(self, endpoint, query=None, body=None, data=None, timeout=None):
        """
        Send a POST request to Drydock. If both body and data are specified,
        body will be used.

        :param string endpoint: The URL string following the hostname and API prefix
        :param dict query: A dict of k, v parameters to add to the query string
        :param string body: A string to use as the request body. Will be treated as raw
        :param data: Something json.dumps(s) can serialize. Result will be used as the request body
        :param timeout: A single or tuple value for connect, read timeout.
            A single value indicates the read timeout only
        :return: A requests.Response object
        """
        auth_refresh = False
        url = self.base_url + endpoint
        while True:
            self.logger.debug('POST ' + url)
            self.logger.debug('Query Params: ' + str(query))
            if body is not None:
                self.logger.debug(
                    "Sending POST with explicit body: \n%s" % body)
                resp = self.__session.post(
                    self.base_url + endpoint,
                    params=query,
                    data=body,
                    timeout=self._timeout(timeout))
            else:
                self.logger.debug(
                    "Sending POST with JSON body: \n%s" % str(data))
                resp = self.__session.post(
                    self.base_url + endpoint,
                    params=query,
                    json=data,
                    timeout=self._timeout(timeout))
            if resp.status_code == 401 and not auth_refresh:
                self.set_auth()
                auth_refresh = True
            else:
                break

        return resp 
Example 23
Project: drydock   Author: airshipit   File: session.py    License: Apache License 2.0 5 votes vote down vote up
def post(self, endpoint, query=None, body=None, data=None, timeout=None):
        """
        Send a POST request to Drydock. If both body and data are specified,
        body will will be used.

        :param string endpoint: The URL string following the hostname and API prefix
        :param dict query: A dict of k, v parameters to add to the query string
        :param string body: A string to use as the request body. Will be treated as raw
        :param data: Something json.dumps(s) can serialize. Result will be used as the request body
        :param timeout: A single or tuple value for connect, read timeout.
            A single value indicates the read timeout only
        :return: A requests.Response object
        """
        auth_refresh = False
        url = self.base_url + endpoint
        while True:
            self.logger.debug('POST ' + url)
            self.logger.debug('Query Params: ' + str(query))
            if body is not None:
                self.logger.debug(
                    "Sending POST with explicit body: \n%s" % body)
                resp = self.__session.post(
                    self.base_url + endpoint,
                    params=query,
                    data=body,
                    timeout=self._timeout(timeout))
            else:
                self.logger.debug(
                    "Sending POST with JSON body: \n%s" % str(data))
                resp = self.__session.post(
                    self.base_url + endpoint,
                    params=query,
                    json=data,
                    timeout=self._timeout(timeout))
            if resp.status_code == 401 and not auth_refresh:
                self.set_auth()
                auth_refresh = True
            else:
                break

        return resp 
Example 24
Project: zmirror   Author: aploium   File: threadlocal.py    License: MIT License 5 votes vote down vote up
def remote_response(self):
        """
        远程服务器的响应, 对象, requests.Response
        :rtype: requests.Response
        """
        return self.__getattribute__("_remote_response") 
Example 25
Project: zmirror   Author: aploium   File: threadlocal.py    License: MIT License 5 votes vote down vote up
def remote_response(self, value):
        """:type value: requests.Response"""
        self.__setattr__("_remote_response", value) 
Example 26
Project: zmirror   Author: aploium   File: test_httpbin.py    License: MIT License 5 votes vote down vote up
def test_homepage(self):
        """https://httpbin.org/"""

        self.rv = self.client.get(
            self.url("/"),
            environ_base=env(),
            headers=headers(),
        )  # type: Response
        self.assertIn(b'httpbin', self.rv.data, msg=self.dump()) 
Example 27
Project: zmirror   Author: aploium   File: test_httpbin.py    License: MIT License 5 votes vote down vote up
def test__enable_keep_alive_per_domain(self):
        """https://httpbin.org/"""
        self.reload_zmirror({"enable_keep_alive_per_domain": True})

        self.rv = self.client.get(
            self.url("/"),
            environ_base=env(),
            headers=headers(),
        )  # type: Response
        self.assertIn(b'httpbin', self.rv.data, msg=self.dump()) 
Example 28
Project: zmirror   Author: aploium   File: test_httpbin.py    License: MIT License 5 votes vote down vote up
def test_main_domain_as_external(self):
        self.rv = self.client.get(
            self.url("/extdomains//" + self.C.target_domain),
            environ_base=env(),
            headers=headers(),
        )  # type: Response
        self.assertEqual(307, self.rv.status_code, self.dump()) 
Example 29
Project: zmirror   Author: aploium   File: test_httpbin.py    License: MIT License 5 votes vote down vote up
def test_user_agent(self):
        """https://httpbin.org/user-agent"""

        self.rv = self.client.get(
            self.url("/user-agent"),
            environ_base=env(),
            headers=headers(),
        )  # type: Response

        self.assertEqual(load_rv_json(self.rv)['user-agent'], DEFAULT_USER_AGENT, msg=self.dump()) 
Example 30
Project: zmirror   Author: aploium   File: test_httpbin.py    License: MIT License 5 votes vote down vote up
def test_remote_set_cookie(self):
        """https://httpbin.org/cookies/set?name=value"""
        self.rv = self.client.get(
            self.url("/cookies/set?k1=value1&k2=value2"),
            environ_base=env(),
            headers=headers(),
        )  # type: Response

        self.assertEqual(2, len(self.rv.headers.get_all("Set-Cookie")), msg=self.dump())
        for set_cookie_header in self.rv.headers.get_all("Set-Cookie"):
            if not ("k1=value1" in set_cookie_header
                    or "k2=value2" in set_cookie_header):
                raise ValueError("cookie set error" + self.dump())
        self.assertEqual(302, self.rv.status_code, msg=self.dump())