本文整理匯總了Python中google.oauth2.credentials方法的典型用法代碼示例。如果您正苦於以下問題:Python oauth2.credentials方法的具體用法?Python oauth2.credentials怎麽用?Python oauth2.credentials使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類google.oauth2
的用法示例。
在下文中一共展示了oauth2.credentials方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_get_api_client
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def test_get_api_client(self, mock_creds, mock_build, mock_http_auth):
"""Test getting a scoped api client."""
mock_creds.from_authorized_user_info.return_value = TestCredentials([
'test_scope1',
])
self.fs.CreateFile(
self._test_config.local_credentials_file_path,
contents=_FAKE_JSON_CONTENTS_ONE)
test_creds = auth.CloudCredentials(self._test_config, ['test_scope1'])
with mock.patch.object(
test_creds, '_request_new_credentials',
return_value=TestCredentials([
'test_scope2', 'test_scope1'])) as mock_request:
test_api_client = test_creds.get_api_client(
'test_service', 'test_version', ['test_scope2'])
del test_api_client # Unused.
mock_request.assert_called_once_with(['test_scope2', 'test_scope1'])
mock_http_auth.assert_called_once_with(
credentials=TestCredentials(['test_scope2', 'test_scope1']))
mock_build.assert_called_once_with(
serviceName='test_service', version='test_version',
http=mock_http_auth.return_value)
示例2: credentials
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def credentials(self):
"""Returns credentials from the OAuth 2.0 session.
:meth:`fetch_token` must be called before accessing this. This method
constructs a :class:`google.oauth2.credentials.Credentials` class using
the session's token and the client config.
Returns:
google.oauth2.credentials.Credentials: The constructed credentials.
Raises:
ValueError: If there is no access token in the session.
"""
return google_auth_oauthlib.helpers.credentials_from_session(
self.oauth2session, self.client_config
)
示例3: test_save_existing_dir
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def test_save_existing_dir(self, runner, local_server_mock):
credentials_tmpdir = tempfile.mkdtemp()
result = runner.invoke(
cli.main,
[
"--client-secrets",
CLIENT_SECRETS_FILE,
"--scope",
"somescope",
"--credentials",
os.path.join(credentials_tmpdir, "credentials.json"),
"--save",
],
)
local_server_mock.assert_called_with(mock.ANY)
assert not result.exception
assert "saved" in result.output
assert result.exit_code == 0
示例4: init_googleAssistant
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def init_googleAssistant():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--credentials', type=existing_file,
metavar='OAUTH2_CREDENTIALS_FILE',
default=os.path.join(
os.path.expanduser('/home/pi/.config'),
'google-oauthlib-tool',
'credentials.json'
),
help='Path to store and read OAuth2 credentials')
args = parser.parse_args()
with open(args.credentials, 'r') as f:
credentials = google.oauth2.credentials.Credentials(token=None,
**json.load(f))
with Assistant(credentials,"magic-mirror-device-id") as assistant:
for event in assistant.start():
process_event(event)
示例5: cli
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def cli(ctx, project_id, verbose, api_endpoint, credentials):
try:
with open(credentials, 'r') as f:
c = google.oauth2.credentials.Credentials(token=None,
**json.load(f))
http_request = google.auth.transport.requests.Request()
c.refresh(http_request)
except Exception as e:
raise click.ClickException('Error loading credentials: %s.\n'
'Run google-oauthlib-tool to initialize '
'new OAuth 2.0 credentials.' % e)
ctx.obj['API_ENDPOINT'] = api_endpoint
ctx.obj['API_VERSION'] = ASSISTANT_API_VERSION
ctx.obj['SESSION'] = None
ctx.obj['PROJECT_ID'] = project_id
ctx.obj['CREDENTIALS'] = c
if verbose:
logging.getLogger().setLevel(logging.DEBUG)
示例6: CreateHttpHeader
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def CreateHttpHeader(self):
"""Creates an OAuth2 HTTP header.
The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
A dictionary containing one entry: the OAuth2 Bearer header under the
'Authorization' key.
Raises:
GoogleAdsError: If the access token has expired.
"""
oauth2_header = {}
if self.creds.expired:
raise googleads.errors.GoogleAdsError('Access token has expired.')
self.creds.apply(oauth2_header)
return oauth2_header
示例7: __init__
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def __init__(self, client_id, client_secret, refresh_token, **kwargs):
"""Initializes a GoogleRefreshTokenClient.
Args:
client_id: A string containing your client ID.
client_secret: A string containing your client secret.
refresh_token: A string containing your refresh token.
**kwargs: Keyword arguments.
Keyword Arguments:
access_token: A string containing your access token.
token_expiry: A datetime instance indicating when the given access token
expires.
proxy_config: A googleads.common.ProxyConfig instance or None if a proxy
isn't being used.
"""
self.creds = google.oauth2.credentials.Credentials(
kwargs.get('access_token'), refresh_token=refresh_token,
client_id=client_id, client_secret=client_secret,
token_uri=self._GOOGLE_OAUTH2_ENDPOINT)
self.creds.expiry = kwargs.get('token_expiry')
self.proxy_config = kwargs.get('proxy_config',
googleads.common.ProxyConfig())
示例8: main
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--credentials', type=existing_file,
metavar='OAUTH2_CREDENTIALS_FILE',
default=os.path.join(
os.path.expanduser('~/.config'),
'google-oauthlib-tool',
'credentials.json'
),
help='Path to store and read OAuth2 credentials')
args = parser.parse_args()
with open(args.credentials, 'r') as f:
credentials = google.oauth2.credentials.Credentials(token=None,
**json.load(f))
with Assistant(credentials) as assistant:
for event in assistant.start():
process_event(event)
示例9: test_write_creates_private_file
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def test_write_creates_private_file(self):
root = self.get_temp_dir()
auth.CredentialsStore(user_config_directory=root).write_credentials(
google.oauth2.credentials.Credentials(
token=None, refresh_token="12345"
)
)
path = os.path.join(
root, "tensorboard", "credentials", "uploader-creds.json"
)
self.assertTrue(os.path.exists(path))
# Skip permissions check on Windows.
if os.name != "nt":
self.assertEqual(0o600, os.stat(path).st_mode & 0o777)
with open(path) as f:
contents = json.load(f)
self.assertEqual("12345", contents["refresh_token"])
示例10: test_write_and_read_roundtrip
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def test_write_and_read_roundtrip(self):
orig_creds = google.oauth2.credentials.Credentials(
token="12345",
refresh_token="67890",
token_uri="https://oauth2.googleapis.com/token",
client_id="my-client",
client_secret="123abc456xyz",
scopes=["userinfo", "email"],
)
root = self.get_temp_dir()
store = auth.CredentialsStore(user_config_directory=root)
store.write_credentials(orig_creds)
creds = store.read_credentials()
self.assertEqual(orig_creds.refresh_token, creds.refresh_token)
self.assertEqual(orig_creds.token_uri, creds.token_uri)
self.assertEqual(orig_creds.client_id, creds.client_id)
self.assertEqual(orig_creds.client_secret, creds.client_secret)
示例11: _build_service_from_document
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def _build_service_from_document(credentials, document_path):
"""Builds an API client from a local discovery document
Args:
credentials (OAuth2Credentials): Credentials that will be used to
authenticate the API calls.
document_path (str): The local path of the discovery document
Returns:
object: A Resource object with methods for interacting with the service.
"""
with open(document_path, 'r') as f:
discovery_data = json.load(f)
return discovery.build_from_document(
service=discovery_data,
credentials=credentials
)
# pylint: disable=too-many-instance-attributes
示例12: http
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def http(self):
"""A thread local instance of httplib2.Http.
Returns:
google_auth_httplib2.AuthorizedHttp: An Http instance authorized by
the credentials.
"""
if self._use_cached_http and hasattr(self._local, 'http'):
return self._local.http
authorized_http = google_auth_httplib2.AuthorizedHttp(
self._credentials, http=http_helpers.build_http())
if self._use_cached_http:
self._local.http = authorized_http
return authorized_http
示例13: _create_assistant
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def _create_assistant(self):
# Create gRPC channel
grpc_channel = google.auth.transport.grpc.secure_authorized_channel(
self.credentials, self.http_request, self.api_endpoint)
self.logger.info('Connecting to %s', self.api_endpoint)
# Create Google Assistant API gRPC client.
self.assistant = embedded_assistant_pb2.EmbeddedAssistantStub(grpc_channel)
示例14: test_cloud_credentials_constructor_invalid_creds
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def test_cloud_credentials_constructor_invalid_creds(self, mock_run_flow):
"""Test that an error is raised if credentials cannot be created."""
del mock_run_flow # Unused.
with self.assertRaises(auth.InvalidCredentials):
auth.CloudCredentials(self._test_config, ['test_scope1'])
示例15: test_remove_creds
# 需要導入模塊: from google import oauth2 [as 別名]
# 或者: from google.oauth2 import credentials [as 別名]
def test_remove_creds(self):
"""Test whether or not to remove the local credentials."""
FLAGS.unparse_flags()
self.assertFalse(auth._remove_creds())
flags.FLAGS(sys.argv[:1] + ['--remove_creds'])
FLAGS.mark_as_parsed()
self.assertTrue(auth._remove_creds())