Create a response object python

By On Monday, September 26th, 2022 Categories : Tanya Jawab

Create a response object python – Apa kabar ibu dan bapak semua, Makasih banyak dah mau berkunjung ke halaman blog www.trendwisata.com ini. Kali ini, kita di blog trendwisata.com pengen membagikan ulasan yang mantab yang menjelaskan tentang Create a response object python. Kami persilakan ibu dan bapak menyimaknya dibawah ini:

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

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

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

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

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

def send_message(self, text: str, retry_count: int = 3) -> Response:
        """Send raw text to bot framework using direct line api"""

        url = "https://kafesentul.com/".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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def remote_response(self):
        """
        远程服务器的响应, 对象, requests.Response
        :rtype: requests.Response
        """
        return self.__getattribute__("_remote_response") 

Example #25

def remote_response(self, value):
        """:type value: requests.Response"""
        self.__setattr__("_remote_response", value) 

Example #26

def test_homepage(self):
        """https://httpbin.org/"""

        self.rv = self.client.get(
            self.url("https://kafesentul.com/"),
            environ_base=env(),
            headers=headers(),
        )  # type: Response
        self.assertIn(b'httpbin', self.rv.data, msg=self.dump()) 

Example #27

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("https://kafesentul.com/"),
            environ_base=env(),
            headers=headers(),
        )  # type: Response
        self.assertIn(b'httpbin', self.rv.data, msg=self.dump()) 

Example #28

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

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

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()) 

How do you create a response in Python?

Just use the responses library to do it for you: import responses @responses. activate def test_my_api(): responses. add(responses.

What is a response object in Python?

This Response object in terms of python is returned by requests. method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.

How do you create a request object in Python?

r = requests.get(url = URL, params = PARAMS) Here we create a response object ‘r’ which will store the request-response. We use requests. … .

data = r.json() Now, in order to retrieve the data from the response object, we need to convert the raw response content into a JSON type data structure..

What is a response object?

The Response Object is used to send a response to the client request from a server. It has many predefined methods, properties, and collections. It has some methods, properties, and collections. Properties. Buffer: It defines that whether the out page would be buffered or not.

Create a response object python | admin | 4.5
shopee flash sale gratis ongkir
x