本文整理汇总了Python中oauth2client.client.OAuth2Credentials方法的典型用法代码示例。如果您正苦于以下问题:Python client.OAuth2Credentials方法的具体用法?Python client.OAuth2Credentials怎么用?Python client.OAuth2Credentials使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauth2client.client
的用法示例。
在下文中一共展示了client.OAuth2Credentials方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_refresh_failure
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def test_refresh_failure(self):
"""
Failure to refresh the access token should be treated as auth error.
"""
def raise_invalid_grant(*args, **kwargs):
raise AccessTokenRefreshError()
with mock.patch('sndlatr.models.get_credentials') as getter, \
self.notify_mock() as notify:
cred = mock.MagicMock(spec=OAuth2Credentials)
getter.return_value = cred
cred.refresh.side_effect = raise_invalid_grant
job = self.create_job(error_cnt=self.JOB_MAX_RETRIES)
resp = self._post_send(job)
self.assertEquals(resp.status_int, 200)
notify.assert_called_with(job, 'auth')
示例2: test_pickle_and_json_interop
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def test_pickle_and_json_interop(self):
# Write a file with a pickled OAuth2Credentials.
credentials = self._create_test_credentials()
credentials_file = open(FILENAME, 'wb')
pickle.dump(credentials, credentials_file)
credentials_file.close()
# Storage should be not be able to read that object, as the capability
# to read and write credentials as pickled objects has been removed.
storage = file_module.Storage(FILENAME)
read_credentials = storage.get()
self.assertIsNone(read_credentials)
# Now write it back out and confirm it has been rewritten as JSON
storage.put(credentials)
with open(FILENAME) as credentials_file:
data = json.load(credentials_file)
self.assertEquals(data['access_token'], 'foo')
self.assertEquals(data['_class'], 'OAuth2Credentials')
self.assertEquals(data['_module'], client.OAuth2Credentials.__module__)
示例3: test_cloud_credentials_constructor_no_local_file
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def test_cloud_credentials_constructor_no_local_file(
self, expected_redirect_uri, run_web_server, mock_run_flow,
mock_server_flow):
"""Test the creation of the CloudCredentials object with no local creds."""
FLAGS.automatic_oauth = run_web_server
mock_run_flow.return_value = oauth2_client.OAuth2Credentials(
access_token='test_access_token',
client_id=self._test_config.client_id,
client_secret=self._test_config.client_secret,
refresh_token='test_refresh_token',
token_expiry=datetime.datetime(year=2018, month=1, day=1),
token_uri='test_token_uri',
user_agent=None,
id_token='test_id_token',
scopes=['test_scope1'])
test_creds = auth.CloudCredentials(self._test_config, ['test_scope1'])
self.assertEqual(self._test_config, test_creds._config)
self.assertEqual('test_access_token', test_creds._credentials.token)
self.assertEqual(
'test_refresh_token', test_creds._credentials.refresh_token)
self.assertEqual('test_id_token', test_creds._credentials.id_token)
self.assertEqual('test_token_uri', test_creds._credentials.token_uri)
self.assertEqual(
self._test_config.client_id, test_creds._credentials.client_id)
self.assertEqual(
self._test_config.client_secret, test_creds._credentials.client_secret)
self.assertEqual(['test_scope1'], test_creds._credentials.scopes)
mock_server_flow.assert_called_once_with(
client_id=self._test_config.client_id,
client_secret=self._test_config.client_secret,
scope=['test_scope1'],
redirect_uri=expected_redirect_uri)
示例4: build_credentials
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def build_credentials():
return OAuth2Credentials('x', 'y', 'z', 'a', 'b', 'c', 'd',
id_token={'sub': '12345',
'email': 'test@example.com'})
示例5: _is_valid_credentials
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def _is_valid_credentials(credentials):
return isinstance(credentials, client.OAuth2Credentials)
示例6: client_with_credentials
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def client_with_credentials(app):
"""This fixture provides a Flask app test client that has a session
pre-configured with use credentials."""
credentials = OAuth2Credentials(
'access_token',
'client_id',
'client_secret',
'refresh_token',
'3600',
None,
'Test',
id_token={'sub': '123', 'email': 'user@example.com'},
scopes=('email', 'profile'))
@contextlib.contextmanager
def inner():
with app.test_client() as client:
with client.session_transaction() as session:
session['profile'] = {
'email': 'abc@example.com',
'name': 'Test User'
}
session['google_oauth2_credentials'] = credentials.to_json()
yield client
return inner
# Mark all test cases in this class as flaky, so that if errors occur they
# can be retried. This is useful when databases are temporarily unavailable.
示例7: _create_test_credentials
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def _create_test_credentials(self, client_id='some_client_id',
expiration=None):
access_token = 'foo'
client_secret = 'cOuDdkfjxxnv+'
refresh_token = '1/0/a.df219fjls0'
token_expiry = expiration or datetime.datetime.utcnow()
token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
user_agent = 'refresh_checker/1.0'
credentials = client.OAuth2Credentials(
access_token, client_id, client_secret,
refresh_token, token_expiry, token_uri,
user_agent)
return credentials
示例8: __init__
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def __init__(self, host, refresh_token, user_agent, source,
host_override=None, extra_headers=None, save_cookies=False,
auth_tries=None, account_type=None, debug_data=True, secure=True,
ignore_certs=False, rpc_tries=3):
"""Creates a new HttpRpcServerOauth2.
Args:
host: The host to send requests to.
refresh_token: A string refresh token to use, or None to guide the user
through the auth flow. (Replaces auth_function on parent class.)
user_agent: The user-agent string to send to the server. Specify None to
omit the user-agent header.
source: Tuple, (client_id, client_secret, scope), for oauth credentials.
host_override: The host header to send to the server (defaults to host).
extra_headers: A dict of extra headers to append to every request. Values
supplied here will override other default headers that are supplied.
save_cookies: If the refresh token should be saved.
auth_tries: The number of times to attempt auth_function before failing.
account_type: Ignored.
debug_data: Whether debugging output should include data contents.
secure: If the requests sent using Send should be sent over HTTPS.
ignore_certs: If the certificate mismatches should be ignored.
rpc_tries: The number of rpc retries upon http server error (i.e.
Response code >= 500 and < 600) before failing.
"""
super(HttpRpcServerOauth2, self).__init__(
host, None, user_agent, None, host_override=host_override,
extra_headers=extra_headers, auth_tries=auth_tries,
debug_data=debug_data, secure=secure, ignore_certs=ignore_certs,
rpc_tries=rpc_tries)
if not isinstance(source, tuple) or len(source) not in (3, 4):
raise TypeError('Source must be tuple (client_id, client_secret, scope).')
self.client_id = source[0]
self.client_secret = source[1]
self.scope = source[2]
oauth2_credential_file = (len(source) > 3 and source[3]
or '~/.appcfg_oauth2_tokens')
if save_cookies:
self.storage = oauth2client_file.Storage(
os.path.expanduser(oauth2_credential_file))
else:
self.storage = NoStorage()
self.refresh_token = refresh_token
if refresh_token:
self.credentials = client.OAuth2Credentials(
None,
self.client_id,
self.client_secret,
refresh_token,
None,
('https://%s/o/oauth2/token' %
os.getenv('APPENGINE_AUTH_SERVER', 'accounts.google.com')),
self.user_agent)
else:
self.credentials = self.storage.get()
示例9: get_credentials
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def get_credentials(credentials=None, client_secret_file=CLIENT_SECRET_FILE, refresh_token=None):
"""Consistently returns valid credentials object.
See Also:
https://developers.google.com/drive/web/quickstart/python
Args:
client_secret_file (str): path to client secrets file, defaults to .gdrive_private
refresh_token (str): path to a user provided refresh token that is already
pre-authenticated
credentials (`~oauth2client.client.OAuth2Credentials`, optional): handle direct
input of credentials, which will check credentials for valid type and
return them
Returns:
`~oauth2client.client.OAuth2Credentials`: google credentials object
"""
# if the utility was provided credentials just return those
if credentials:
if _is_valid_credentials(credentials):
# auth for gspread
return credentials
else:
print("Invalid credentials supplied. Will generate from default token.")
token = refresh_token or DEFAULT_TOKEN
dir_name = os.path.dirname(DEFAULT_TOKEN)
try:
os.makedirs(dir_name)
except OSError:
if not os.path.isdir(dir_name):
raise
store = file.Storage(token)
credentials = store.get()
try:
import argparse
flags = argparse.ArgumentParser(
parents=[tools.argparser]).parse_known_args()[0]
except ImportError:
flags = None
logr.error(
'Unable to parse oauth2client args; `pip install argparse`')
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(
client_secret_file, SCOPES)
flow.redirect_uri = client.OOB_CALLBACK_URN
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatability with Python 2.6
credentials = tools.run(flow, store)
logr.info('Storing credentials to ' + DEFAULT_TOKEN)
return credentials
示例10: create_service_credentials
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2Credentials [as 别名]
def create_service_credentials(private_key_file=None, client_email=None,
client_secret_file=CLIENT_SECRET_FILE):
"""Create credentials from service account information.
See Also:
https://developers.google.com/api-client-library/python/auth/service-accounts
Args:
client_secret_file (str): path to json file with just the client_email when
providing the `private_key_file` separately, or this file can have both the
`client_email` and `private_key` contained in it. Defaults to .gdrive_private
client_email (str): service email account
private_key_file (str): path to the p12 private key, defaults to same name of file
used for regular authentication
Returns:
`~oauth2client.client.OAuth2Credentials`: google credentials object
"""
if private_key_file is not None:
with open(os.path.expanduser(private_key_file)) as f:
private_key = f.read()
else:
private_key = None
if client_email is None:
with open(os.path.expanduser(client_secret_file)) as client_file:
client_data = json.load(client_file)
if 'installed' in client_data:
# handle regular json format where key is separate
client_email = client_data['installed']['client_id']
if private_key is None:
raise RuntimeError('You must have the private key file \
with the regular json file. Try creating a new \
public/private key pair and downloading as json.')
else:
# handle newer case where json file has everything in it
client_email = client_data['client_email']
private_key = client_data['private_key']
if client_email is None or private_key is None:
raise RuntimeError(
'Client email and/or private key not provided by inputs.')
credentials = client.SignedJwtAssertionCredentials(
client_email, private_key, SCOPES)
return credentials