本文整理匯總了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