本文整理汇总了Python中requests.Response方法的典型用法代码示例。如果您正苦于以下问题:Python requests.Response方法的具体用法?Python requests.Response怎么用?Python requests.Response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.Response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例2: get
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例3: post_sandbox_payment
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例4: _format_code_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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),
)
示例5: send_message
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例6: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例7: _get_metadata
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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)
示例8: _http_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例9: parse_object
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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 ()
示例10: parse_system
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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),
)
示例11: parse_search
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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,
)
示例12: send
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例13: _async_send
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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
示例14: handle_errors
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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)
示例15: get_raw
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Response [as 别名]
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))