当前位置: 首页>>代码示例>>Python>>正文


Python oauth2.credentials方法代码示例

本文整理汇总了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) 
开发者ID:google,项目名称:loaner,代码行数:24,代码来源:auth_test.py

示例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
        ) 
开发者ID:googleapis,项目名称:google-auth-library-python-oauthlib,代码行数:18,代码来源:flow.py

示例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 
开发者ID:googleapis,项目名称:google-auth-library-python-oauthlib,代码行数:20,代码来源:test_tool.py

示例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) 
开发者ID:gauravsacc,项目名称:MMM-GoogleAssistant,代码行数:21,代码来源:assistant.py

示例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) 
开发者ID:googlesamples,项目名称:assistant-sdk-python,代码行数:20,代码来源:devicetool.py

示例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 
开发者ID:googleads,项目名称:googleads-python-lib,代码行数:23,代码来源:oauth2.py

示例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()) 
开发者ID:googleads,项目名称:googleads-python-lib,代码行数:25,代码来源:oauth2.py

示例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) 
开发者ID:respeaker,项目名称:mic_array,代码行数:21,代码来源:google_assistant_for_raspberry_pi.py

示例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"]) 
开发者ID:tensorflow,项目名称:tensorboard,代码行数:19,代码来源:auth_test.py

示例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) 
开发者ID:tensorflow,项目名称:tensorboard,代码行数:19,代码来源:auth_test.py

示例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 
开发者ID:forseti-security,项目名称:forseti-security,代码行数:23,代码来源:_base_repository.py

示例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 
开发者ID:forseti-security,项目名称:forseti-security,代码行数:18,代码来源:_base_repository.py

示例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) 
开发者ID:warchildmd,项目名称:google-assistant-hotword-raspi,代码行数:10,代码来源:assistant.py

示例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']) 
开发者ID:google,项目名称:loaner,代码行数:7,代码来源:auth_test.py

示例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()) 
开发者ID:google,项目名称:loaner,代码行数:9,代码来源:auth_test.py


注:本文中的google.oauth2.credentials方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。