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


Python grpc.intercept_channel方法代码示例

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


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

示例1: intercepted_echo

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def intercepted_echo(use_mtls):
    # The interceptor adds 'showcase-trailer' client metadata. Showcase server
    # echos any metadata with key 'showcase-trailer', so the same metadata
    # should appear as trailing metadata in the response.
    interceptor = MetadataClientInterceptor("showcase-trailer", "intercepted")
    host = "localhost:7469"
    channel = (
        grpc.secure_channel(host, ssl_credentials)
        if use_mtls
        else grpc.insecure_channel(host)
    )
    intercept_channel = grpc.intercept_channel(channel, interceptor)
    transport = EchoClient.get_transport_class("grpc")(
        channel=intercept_channel
    )
    return EchoClient(transport=transport) 
开发者ID:googleapis,项目名称:gapic-generator-python,代码行数:18,代码来源:conftest.py

示例2: __init__

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def __init__(self,org_id,service_id, service_metadata,group, service_stub, payment_strategy,
                 options,mpe_contract,account,sdk_web3):
        self.org_id = org_id
        self.service_id = service_id
        self.options = options
        self.group = group
        self.service_metadata = service_metadata

        self.payment_strategy = payment_strategy
        self.expiry_threshold = self.group["payment"]["payment_expiration_threshold"]
        self._base_grpc_channel = self._get_grpc_channel()
        self.grpc_channel = grpc.intercept_channel(self._base_grpc_channel,
                                                   generic_client_interceptor.create(self._intercept_call))
        self.payment_channel_provider=PaymentChannelProvider(sdk_web3,self._generate_payment_channel_state_service_client(),mpe_contract)
        self.service = self._generate_grpc_stub(service_stub)
        self.payment_channels = []
        self.last_read_block = 0
        self.account=account
        self.sdk_web3=sdk_web3
        self.mpe_address=mpe_contract.contract.address 
开发者ID:singnet,项目名称:snet-cli,代码行数:22,代码来源:service_client.py

示例3: wrap_make_secure_channel

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def wrap_make_secure_channel(make_secure_channel_func, tracer=None):
    """Wrap the google.cloud._helpers.make_secure_channel."""
    def call(*args, **kwargs):
        channel = make_secure_channel_func(*args, **kwargs)

        try:
            host = kwargs.get('host')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, host)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap secure channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call 
开发者ID:census-instrumentation,项目名称:opencensus-python,代码行数:19,代码来源:trace.py

示例4: wrap_insecure_channel

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def wrap_insecure_channel(insecure_channel_func, tracer=None):
    """Wrap the grpc.insecure_channel."""
    def call(*args, **kwargs):
        channel = insecure_channel_func(*args, **kwargs)

        try:
            target = kwargs.get('target')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap insecure channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call 
开发者ID:census-instrumentation,项目名称:opencensus-python,代码行数:19,代码来源:trace.py

示例5: wrap_create_channel

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def wrap_create_channel(create_channel_func, tracer=None):
    """Wrap the google.api_core.grpc_helpers.create_channel."""
    def call(*args, **kwargs):
        channel = create_channel_func(*args, **kwargs)

        try:
            target = kwargs.get('target')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap create_channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call 
开发者ID:census-instrumentation,项目名称:opencensus-python,代码行数:19,代码来源:trace.py

示例6: main

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def main():
    exporter = stackdriver_exporter.StackdriverExporter()
    tracer = Tracer(exporter=exporter)
    tracer_interceptor = client_interceptor.OpenCensusClientInterceptor(
        tracer,
        host_port=HOST_PORT)
    channel = grpc.insecure_channel(HOST_PORT)
    channel = grpc.intercept_channel(channel, tracer_interceptor)
    stub = hello_world_pb2_grpc.GreeterStub(channel)
    response = stub.SayHello(hello_world_pb2.HelloRequest(name='you'))
    print("Message received: " + response.message) 
开发者ID:census-instrumentation,项目名称:opencensus-python,代码行数:13,代码来源:hello_world_client.py

示例7: _intercepted_channel

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def _intercepted_channel(self, tracer=None):
        return grpc.intercept_channel(
            self._channel,
            client_interceptor.OpenCensusClientInterceptor(tracer=tracer)) 
开发者ID:census-instrumentation,项目名称:opencensus-python,代码行数:6,代码来源:test_client_interceptor.py

示例8: get_conn

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [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

示例9: get_service

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def get_service(self, name, version=_DEFAULT_VERSION, interceptors=None):
        """Returns a service client instance for the specified service_name.

        Args:
            name: a str indicating the name of the service for which a
                service client is being retrieved; e.g. you may specify
                "CampaignService" to retrieve a CampaignServiceClient instance.
            version: a str indicating the version of the Google Ads API to be
                used.
            interceptors: an optional list of interceptors to include in
                requests. NOTE: this parameter is not intended for non-Google
                use and is not officially supported.

        Returns:
            A service client instance associated with the given service_name.

        Raises:
            AttributeError: If the specified name doesn't exist.
        """
        api_module = self._get_api_services_by_version(version)
        interceptors = interceptors or []

        try:
            service_client = getattr(api_module,
                                     _SERVICE_CLIENT_TEMPLATE.format(name))
        except AttributeError:
            raise ValueError('Specified service {}" does not exist in Google '
                             'Ads API {}.'.format(name, version))

        try:
            service_transport_class = getattr(
                api_module, _SERVICE_GRPC_TRANSPORT_TEMPLATE.format(name))
        except AttributeError:
            raise ValueError('Grpc transport does not exist for the specified '
                             'service "{}".'.format(name))

        endpoint = (self.endpoint if self.endpoint
                    else service_client.SERVICE_ADDRESS)

        channel = service_transport_class.create_channel(
            address=endpoint,
            credentials=self.credentials,
            options=_GRPC_CHANNEL_OPTIONS)

        interceptors = interceptors + [
            MetadataInterceptor(self.developer_token, self.login_customer_id),
            LoggingInterceptor(_logger, version, endpoint),
            ExceptionInterceptor(version)]

        channel = grpc.intercept_channel(
            channel,
            *interceptors)

        service_transport = service_transport_class(channel=channel)

        return service_client(transport=service_transport) 
开发者ID:googleads,项目名称:google-ads-python,代码行数:58,代码来源:client.py

示例10: _setup_client_channel_config

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import intercept_channel [as 别名]
def _setup_client_channel_config(self):
        """get grpc client configuration from server and setup channel and stub for use.
        """
        tmp_insec_channel = grpc.insecure_channel(self.address)
        tmp_channel = grpc.intercept_channel(tmp_insec_channel, self.header_adder_int)
        tmp_stub = hangar_service_pb2_grpc.HangarServiceStub(tmp_channel)
        t_init, t_tot = time.time(), 0
        while t_tot < self.wait_ready_timeout:
            try:
                request = hangar_service_pb2.GetClientConfigRequest()
                response = tmp_stub.GetClientConfig(request)
                self.cfg['push_max_nbytes'] = int(response.config['push_max_nbytes'])
                self.cfg['optimization_target'] = response.config['optimization_target']

                enable_compression = response.config['enable_compression']
                if enable_compression == 'NoCompression':
                    compression_val = grpc.Compression.NoCompression
                elif enable_compression == 'Deflate':
                    compression_val = grpc.Compression.Deflate
                elif enable_compression == 'Gzip':
                    compression_val = grpc.Compression.Gzip
                else:
                    compression_val = grpc.Compression.NoCompression
                self.cfg['enable_compression'] = compression_val

            except grpc.RpcError as err:
                if not (err.code() == grpc.StatusCode.UNAVAILABLE) and (self.wait_ready is True):
                    logger.error(err)
                    raise err
            else:
                break
            time.sleep(0.05)
            t_tot = time.time() - t_init
        else:
            err = ConnectionError(f'Server did not connect after: {self.wait_ready_timeout} sec.')
            logger.error(err)
            raise err

        tmp_channel.close()
        tmp_insec_channel.close()
        configured_channel = grpc.insecure_channel(
            self.address,
            options=[
                ('grpc.optimization_target', self.cfg['optimization_target']),
                ("grpc.keepalive_time_ms", 1000 * 60 * 1),
                ("grpc.keepalive_timeout_ms", 1000 * 10),
                ("grpc.http2_min_sent_ping_interval_without_data_ms", 1000 * 10),
                ("grpc.http2_max_pings_without_data", 0),
                ("grpc.keepalive_permit_without_calls", 1),
            ],
            compression=self.cfg['enable_compression'])
        self.channel = grpc.intercept_channel(configured_channel, self.header_adder_int)
        self.stub = hangar_service_pb2_grpc.HangarServiceStub(self.channel) 
开发者ID:tensorwerk,项目名称:hangar-py,代码行数:55,代码来源:client.py


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