Python requests.Response() Examples

The following are 30 code examples of requests.Response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests , or try the search function .
Example #1
Source File: promenade_client.py    From drydock with Apache License 2.0 7 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
Source File: expiring.py    From tekore with 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 #3
Source File: models.py    From schemathesis with 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 #4
Source File: models.py    From schemathesis with 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 #5
Source File: models.py    From schemathesis with 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 #6
Source File: session.py    From drydock with 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 #7
Source File: test_integration_sandbox.py    From django-payfast with 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 #8
Source File: test_handlers.py    From jupyterlab_code_formatter with 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 #9
Source File: direct_line_client.py    From botbuilder-python with 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 #10
Source File: fake_requests.py    From zun with 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 #11
Source File: client.py    From rets with 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 #12
Source File: parse_object.py    From rets with 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 #13
Source File: core.py    From schemathesis with 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 #14
Source File: extending.py    From tekore with 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
Source File: extending.py    From tekore with 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 #16
Source File: extending.py    From tekore with 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 #17
Source File: instaloadercontext.py    From instaloader with 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 #18
Source File: parse.py    From rets with 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 #19
Source File: parse.py    From rets with 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 #20
Source File: client.py    From rets with 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 #21
Source File: utils.py    From spectacles with MIT License 5 votes vote down vote up
def details_from_http_error(response: requests.Response) -> Optional[Dict[str, Any]]:
    try:
        details = response.json()
    # Requests raises a ValueError if the response is invalid JSON
    except ValueError:
        details = None
    return details 
Example #22
Source File: models.py    From schemathesis with MIT License 5 votes vote down vote up
def from_requests(cls, response: requests.Response) -> "Interaction":
        return cls(request=Request.from_prepared_request(response.request), response=Response.from_requests(response)) 
Example #23
Source File: exceptions.py    From spectacles with MIT License 5 votes vote down vote up
def __init__(
        self,
        name: str,
        title: str,
        status: int,
        detail: str,
        response: requests.Response,
    ):
        request: requests.PreparedRequest = response.request
        super().__init__("looker-api-errors/" + name, title, detail)
        self.status = status
        self.looker_api_response: Optional[JsonDict] = details_from_http_error(response)
        self.request = {"url": request.url, "method": request.method} 
Example #24
Source File: models.py    From schemathesis with MIT License 5 votes vote down vote up
def from_wsgi(cls, case: Case, response: WSGIResponse, headers: Dict[str, Any], elapsed: float) -> "Interaction":
        session = requests.Session()
        session.headers.update(headers)
        return cls(request=Request.from_case(case, session), response=Response.from_wsgi(response, elapsed)) 
Example #25
Source File: instaloadercontext.py    From instaloader with MIT License 5 votes vote down vote up
def write_raw(self, resp: Union[bytes, requests.Response], filename: str) -> None:
        """Write raw response data into a file.

        .. versionadded:: 4.2.1"""
        self.log(filename, end=' ', flush=True)
        with open(filename, 'wb') as file:
            if isinstance(resp, requests.Response):
                shutil.copyfileobj(resp.raw, file)
            else:
                file.write(resp) 
Example #26
Source File: probe_search.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def test_location_arg_with_radius(self):
        """User passed location arg"""
        with mock.patch('requests.get') as mock_get:
            mock_get.return_value = requests.Response()
            with mock.patch('requests.Response.json') as mock_json:
                mock_json.return_value = {"results": [
                    {"geometry": {"location": {"lat": 1, "lng": 2}}}
                ]}
                cmd = Command()
                cmd.init_args(["--location", "blaaaa", "--radius", "4"])
                self.assertEquals(
                    cmd.build_request_args(),
                    {"radius": "1,2:4"}
                ) 
Example #27
Source File: schemas.py    From schemathesis with MIT License 5 votes vote down vote up
def call(self) -> requests.Response:
        return requests.post(self.path, json={"query": self.data}) 
Example #28
Source File: helper.py    From kubeshift with GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_response(code, content):
    r = requests.Response()
    r.status_code = code
    if content is not None:
        r.raw = six.BytesIO(six.b(json.dumps(content)))
    return r 
Example #29
Source File: __init__.py    From schemathesis with MIT License 5 votes vote down vote up
def register_check(function: Callable[[Union[requests.Response, WSGIResponse], models.Case], None]) -> None:
    """Register a new check for schemathesis CLI."""
    checks_module.ALL_CHECKS += (function,)
    CHECKS_TYPE.choices += (function.__name__,)  # type: ignore 
Example #30
Source File: concrete.py    From tekore with MIT License 5 votes vote down vote up
def send(self, request: Request) -> Response:
        """Send request with instance client."""
        return await self.client.request(
            request.method,
            request.url,
            data=request.data or None,
            params=request.params or None,
            headers=request.headers,
            **self.httpx_kwargs,
        )