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


Python auth.default方法代码示例

本文整理汇总了Python中google.auth.default方法的典型用法代码示例。如果您正苦于以下问题:Python auth.default方法的具体用法?Python auth.default怎么用?Python auth.default使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在google.auth的用法示例。


在下文中一共展示了auth.default方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_columns

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def get_columns(self, connection, table_name, schema=None, **kw):
        table = self._get_table(connection, table_name, schema)
        columns = self._get_columns_helper(table.schema, [])
        result = []
        for col in columns:
            try:
                coltype = _type_map[col.field_type]
            except KeyError:
                util.warn("Did not recognize type '%s' of column '%s'" % (col.field_type, col.name))

            result.append({
                'name': col.name,
                'type': types.ARRAY(coltype) if col.mode == 'REPEATED' else coltype,
                'nullable': col.mode == 'NULLABLE' or col.mode == 'REPEATED',
                'default': None,
            })

        return result 
开发者ID:mxmzdlv,项目名称:pybigquery,代码行数:20,代码来源:sqlalchemy_bigquery.py

示例2: _check_adc

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def _check_adc():
  """Return whether the application default credential exists and is valid."""
  # google-auth wants to warn the user if no project is set, which makes sense
  # for cloud-only users, but not in our case. We temporarily chnage the logging
  # level here to silence.
  logger = _logging.getLogger()
  log_level = logger.level
  logger.setLevel(_logging.ERROR)
  try:
    creds, _ = _google_auth.default()
  except _google_auth.exceptions.DefaultCredentialsError:
    return False
  finally:
    logger.setLevel(log_level)
  transport = _auth_requests.Request()
  try:
    creds.refresh(transport)
  except Exception as e:  # pylint:disable=broad-except
    _logging.info('Failure refreshing credentials: %s', e)
  return creds.valid 
开发者ID:googlecolab,项目名称:colabtools,代码行数:22,代码来源:auth.py

示例3: authenticate

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def authenticate(self, user_account=None, service_account=None, **kwargs):
        """
        Implements authentication for the GCP provider
        Refer to https://google-auth.readthedocs.io/en/stable/reference/google.auth.html.
        """

        try:

            # Set logging level to error for libraries as otherwise generates a lot of warnings
            logging.getLogger('googleapiclient').setLevel(logging.ERROR)
            logging.getLogger('google.auth').setLevel(logging.ERROR)
            logging.getLogger('google_auth_httplib2').setLevel(logging.ERROR)
            logging.getLogger('urllib3').setLevel(logging.ERROR)

            if user_account:
                # disable GCP warning about using User Accounts
                warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials")
            elif service_account:
                client_secrets_path = os.path.abspath(service_account)
                os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = client_secrets_path
            else:
                raise AuthenticationException('Failed to authenticate to GCP - no supported account type')

            credentials, default_project_id = auth.default()

            if not credentials:
                raise AuthenticationException('No credentials')

            credentials.is_service_account = service_account is not None
            credentials.default_project_id = default_project_id

            return credentials

        except Exception as e:
            raise AuthenticationException(e) 
开发者ID:nccgroup,项目名称:ScoutSuite,代码行数:37,代码来源:authentication_strategy.py

示例4: _add_default_dataset_to_job_config

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def _add_default_dataset_to_job_config(job_config, project_id, dataset_id):
        # If dataset_id is set, then we know the job_config isn't None
        if dataset_id:
            # If project_id is missing, use default project_id for the current environment
            if not project_id:
                _, project_id = auth.default()

            job_config.default_dataset = '{}.{}'.format(project_id, dataset_id) 
开发者ID:mxmzdlv,项目名称:pybigquery,代码行数:10,代码来源:sqlalchemy_bigquery.py

示例5: _get_field

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def _get_field(self, field_name, default=None):
        """
        Fetches a field from extras, and returns it. This is some Airflow
        magic. The grpc hook type adds custom UI elements
        to the hook page, which allow admins to specify scopes, credential pem files, etc.
        They get formatted as shown below.
        """
        full_field_name = 'extra__grpc__{}'.format(field_name)
        if full_field_name in self.extras:
            return self.extras[full_field_name]
        else:
            return default 
开发者ID:apache,项目名称:airflow,代码行数:14,代码来源:grpc.py

示例6: __init__

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def __init__(self):
        credentials, effective_project_id = default()

        self._credentials = credentials
        self._project_id = effective_project_id 
开发者ID:apls777,项目名称:spotty,代码行数:7,代码来源:gcp_credentials.py

示例7: get_project_id

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def get_project_id():
    """Return current project_id."""
    _, project_id = auth.default()
    return project_id 
开发者ID:GoogleCloudPlatform,项目名称:professional-services,代码行数:6,代码来源:config.py

示例8: _get_project_id

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def _get_project_id():
    # get project id from default setting
    try:
        _, project_id = google_auth.default()
    except google_auth.exceptions.DefaultCredentialsError:
        raise ValueError("Couldn't find Google Cloud credentials, set the "
                         "project ID with 'gcloud set project'")
    return project_id 
开发者ID:GoogleCloudPlatform,项目名称:cloud-opensource-python,代码行数:10,代码来源:compatibility_checker_server.py

示例9: get_conn

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def get_conn(self):
        base_url = self.conn.host

        if self.conn.port:
            base_url = base_url + ":" + str(self.conn.port)

        auth_type = self._get_field("auth_type")

        if auth_type == "NO_AUTH":
            channel = grpc.insecure_channel(base_url)
        elif auth_type in {"SSL", "TLS"}:
            credential_file_name = self._get_field("credential_pem_file")
            creds = grpc.ssl_channel_credentials(open(credential_file_name).read())
            channel = grpc.secure_channel(base_url, creds)
        elif auth_type == "JWT_GOOGLE":
            credentials, _ = google_auth.default()
            jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials(
                credentials)
            channel = google_auth_transport_grpc.secure_authorized_channel(
                jwt_creds, None, base_url)
        elif auth_type == "OATH_GOOGLE":
            scopes = self._get_field("scopes").split(",")
            credentials, _ = google_auth.default(scopes=scopes)
            request = google_auth_transport_requests.Request()
            channel = google_auth_transport_grpc.secure_authorized_channel(
                credentials, request, base_url)
        elif auth_type == "CUSTOM":
            if not self.custom_connection_func:
                raise AirflowConfigException(
                    "Customized connection function not set, not able to establish a channel")
            channel = self.custom_connection_func(self.conn)
        else:
            raise AirflowConfigException(
                "auth_type not supported or not provided, channel cannot be established,\
                given value: %s" % str(auth_type))

        if self.interceptors:
            for interceptor in self.interceptors:
                channel = grpc.intercept_channel(channel,
                                                 interceptor)

        return channel 
开发者ID:apache,项目名称:airflow,代码行数:44,代码来源:grpc.py

示例10: authenticate_user

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def authenticate_user(clear_output=True):
  """Ensures that the given user is authenticated.

  Currently, this ensures that the Application Default Credentials
  (https://developers.google.com/identity/protocols/application-default-credentials)
  are available and valid.

  Args:
    clear_output: (optional, default: True) If True, clear any output related to
        the authorization process if it completes successfully. Any errors will
        remain (for debugging purposes).

  Returns:
    None.

  Raises:
    errors.AuthorizationError: If authorization fails.
  """
  if _check_adc():
    return
  _os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = _get_adc_path()
  if not _check_adc():
    context_manager = _output.temporary if clear_output else _noop
    with context_manager():
      _gcloud_login()
    _install_adc()
    colab_tpu_addr = _os.environ.get('COLAB_TPU_ADDR', '')
    if 'COLAB_SKIP_AUTOMATIC_TPU_AUTH' not in _os.environ and colab_tpu_addr:
      # If we've got a TPU attached, we want to run a TF operation to provide
      # our new credentials to the TPU for GCS operations.
      import tensorflow as tf  # pylint: disable=g-import-not-at-top
      if tf.__version__.startswith('1'):
        with tf.compat.v1.Session('grpc://{}'.format(colab_tpu_addr)) as sess:
          with open(_get_adc_path()) as auth_info:
            tf.contrib.cloud.configure_gcs(
                sess, credentials=_json.load(auth_info))
      else:
        # pytype: skip-file
        import tensorflow_gcs_config as _tgc  # pylint: disable=g-import-not-at-top
        _tgc.configure_gcs_from_colab_auth()
  if _check_adc():
    return
  raise _errors.AuthorizationError('Failed to fetch user credentials') 
开发者ID:googlecolab,项目名称:colabtools,代码行数:45,代码来源:auth.py

示例11: main

# 需要导入模块: from google import auth [as 别名]
# 或者: from google.auth import default [as 别名]
def main():

    class Handler(wsgiref.simple_server.WSGIRequestHandler):
        def log_message(self, format, *args):
            # Override the default log_message method to avoid logging
            # remote addresses.
            sys.stderr.write("[%s] %s\n" % (self.log_date_time_string(),
                                            format % args))

    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument(
        '--host',
        default='0.0.0.0',
        help='host name to which the server should bind')
    parser.add_argument(
        '--port',
        type=int,
        default=8888,
        help='port to which the server should bind')
    export_metrics = os.environ.get('EXPORT_METRICS') is not None

    args = parser.parse_args()
    argsdict = vars(args)
    argsdict['export_metrics'] = export_metrics
    logging.info('Running server with:\n%s', pprint.pformat(argsdict))

    if export_metrics:
        _enable_exporter()

    # The views need to be registered with the view manager for data to be
    # collected. Once a view is registered, it reports data to any registered
    # exporters.
    for view in views.ALL_VIEWS:
        STATS.view_manager.register_view(view)

    logging.basicConfig(
        level=logging.INFO,
        format='%(levelname)-8s %(asctime)s ' +
               '%(filename)s:%(lineno)s] %(message)s')

    with wsgiref.simple_server.make_server(
            args.host,
            args.port,
            app,
            handler_class=Handler) as httpd:
        httpd.serve_forever() 
开发者ID:GoogleCloudPlatform,项目名称:cloud-opensource-python,代码行数:48,代码来源:compatibility_checker_server.py


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