本文整理汇总了Python中google.auth.transport.requests.Session方法的典型用法代码示例。如果您正苦于以下问题:Python requests.Session方法的具体用法?Python requests.Session怎么用?Python requests.Session使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.auth.transport.requests
的用法示例。
在下文中一共展示了requests.Session方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def __init__(self, credentials,
refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
refresh_timeout=None,
**kwargs):
super(AuthorizedSession, self).__init__(**kwargs)
self.credentials = credentials
self._refresh_status_codes = refresh_status_codes
self._max_refresh_attempts = max_refresh_attempts
self._refresh_timeout = refresh_timeout
auth_request_session = requests.Session()
# Using an adapter to make HTTP requests robust to network errors.
# This adapter retrys HTTP requests when network errors occur
# and the requests seems safely retryable.
retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
auth_request_session.mount("https://", retry_adapter)
# Request instance used by internal methods (for example,
# credentials.refresh).
# Do not pass `self` as the session here, as it can lead to infinite
# recursion.
self._auth_request = Request(auth_request_session)
示例2: authorized_session
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def authorized_session(self):
"""Returns a :class:`requests.Session` authorized with credentials.
:meth:`fetch_token` must be called before this method. This method
constructs a :class:`google.auth.transport.requests.AuthorizedSession`
class using this flow's :attr:`credentials`.
Returns:
google.auth.transport.requests.AuthorizedSession: The constructed
session.
"""
return google.auth.transport.requests.AuthorizedSession(self.credentials)
示例3: test_timeout
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def test_timeout(self):
http = mock.create_autospec(requests.Session, instance=True)
request = google.auth.transport.requests.Request(http)
request(url="http://example.com", method="GET", timeout=5)
assert http.request.call_args[1]["timeout"] == 5
示例4: test_constructor_with_auth_request
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def test_constructor_with_auth_request(self):
http = mock.create_autospec(requests.Session)
auth_request = google.auth.transport.requests.Request(http)
authed_session = google.auth.transport.requests.AuthorizedSession(
mock.sentinel.credentials, auth_request=auth_request
)
assert authed_session._auth_request == auth_request
示例5: test_request_default_timeout
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def test_request_default_timeout(self):
credentials = mock.Mock(wraps=CredentialsStub())
response = make_response()
adapter = AdapterStub([response])
authed_session = google.auth.transport.requests.AuthorizedSession(credentials)
authed_session.mount(self.TEST_URL, adapter)
patcher = mock.patch("google.auth.transport.requests.requests.Session.request")
with patcher as patched_request:
authed_session.request("GET", self.TEST_URL)
expected_timeout = google.auth.transport.requests._DEFAULT_TIMEOUT
assert patched_request.call_args[1]["timeout"] == expected_timeout
示例6: __init__
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def __init__(self, session=None):
if not session:
session = requests.Session()
self.session = session
示例7: __call__
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def __call__(
self,
url,
method="GET",
body=None,
headers=None,
timeout=_DEFAULT_TIMEOUT,
**kwargs
):
"""Make an HTTP request using requests.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping[str, str]): Request headers.
timeout (Optional[int]): The number of seconds to wait for a
response from the server. If not specified or if None, the
requests default timeout will be used.
kwargs: Additional arguments passed through to the underlying
requests :meth:`~requests.Session.request` method.
Returns:
google.auth.transport.Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
try:
_LOGGER.debug("Making request: %s %s", method, url)
response = self.session.request(
method, url, data=body, headers=headers, timeout=timeout, **kwargs
)
return _Response(response)
except requests.exceptions.RequestException as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)
示例8: Refresh
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def Refresh(self):
"""Uses the Refresh Token to retrieve and set a new Access Token.
Raises:
google.auth.exceptions.RefreshError: If the refresh fails.
"""
with requests.Session() as session:
session.proxies = self.proxy_config.proxies
session.verify = not self.proxy_config.disable_certificate_validation
session.cert = self.proxy_config.cafile
self.creds.refresh(
google.auth.transport.requests.Request(session=session))
示例9: __call__
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def __call__(self, url, method='GET', body=None, headers=None,
timeout=None, **kwargs):
"""Make an HTTP request using requests.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping[str, str]): Request headers.
timeout (Optional[int]): The number of seconds to wait for a
response from the server. If not specified or if None, the
requests default timeout will be used.
kwargs: Additional arguments passed through to the underlying
requests :meth:`~requests.Session.request` method.
Returns:
google.auth.transport.Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
try:
_LOGGER.debug('Making request: %s %s', method, url)
response = self.session.request(
method, url, data=body, headers=headers, timeout=timeout,
**kwargs)
return _Response(response)
except requests.exceptions.RequestException as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)
示例10: _authenticate_session
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def _authenticate_session(self, session, username, password):
"""Post username/password to authenticate the HTTP seesion.
Args:
session: Instance of requests.Session.
username: User username.
password: User password.
"""
# Do a POST to the login handler to set up the session cookies
data = {'username': username, 'password': password}
session.post('{0:s}/login/'.format(self._host_uri), data=data)
示例11: _set_csrf_token
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def _set_csrf_token(self, session):
"""Retrieve CSRF token from the server and append to HTTP headers.
Args:
session: Instance of requests.Session.
"""
# Scrape the CSRF token from the response
response = session.get(self._host_uri)
soup = bs4.BeautifulSoup(response.text, features='html.parser')
tag = soup.find(id='csrf_token')
csrf_token = None
if tag:
csrf_token = tag.get('value')
else:
tag = soup.find('meta', attrs={'name': 'csrf-token'})
if tag:
csrf_token = tag.attrs.get('content')
if not csrf_token:
return
session.headers.update({
'x-csrftoken': csrf_token,
'referer': self._host_uri
})
示例12: _create_session
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Session [as 别名]
def _create_session(
self, username, password, verify, client_id, client_secret,
auth_mode):
"""Create authenticated HTTP session for server communication.
Args:
username: User to authenticate as.
password: User password.
verify: Verify server SSL certificate.
client_id: The client ID if OAUTH auth is used.
client_secret: The OAUTH client secret if OAUTH is used.
auth_mode: The authentication mode to use. Supported values are
'timesketch' (Timesketch login form), 'http-basic'
(HTTP Basic authentication) and oauth.
Returns:
Instance of requests.Session.
"""
if auth_mode == 'oauth':
return self._create_oauth_session(client_id, client_secret)
if auth_mode == 'oauth_local':
return self._create_oauth_session(
client_id=client_id, client_secret=client_secret,
run_server=False, skip_open=True)
session = requests.Session()
# If using HTTP Basic auth, add the user/pass to the session
if auth_mode == 'http-basic':
session.auth = (username, password)
session.verify = verify # Depending if SSL cert is verifiable
# Get and set CSRF token and authenticate the session if appropriate.
self._set_csrf_token(session)
if auth_mode == 'timesketch':
self._authenticate_session(session, username, password)
return session