當前位置: 首頁>>代碼示例>>Python>>正文


Python grpc.server方法代碼示例

本文整理匯總了Python中grpc.server方法的典型用法代碼示例。如果您正苦於以下問題:Python grpc.server方法的具體用法?Python grpc.server怎麽用?Python grpc.server使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在grpc的用法示例。


在下文中一共展示了grpc.server方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def main(unused_argv):
  servers = []
  server_creds = loas2.loas2_server_credentials()
  port = FLAGS.port
  if not FLAGS.run_on_borg:
    port = 20000 + FLAGS.server_id
  server = grpc.server(
      futures.ThreadPoolExecutor(max_workers=10), ports=(port,))
  servicer = ars_evaluation_service.ParameterEvaluationServicer(
      FLAGS.config_name, worker_id=FLAGS.server_id)
  ars_evaluation_service_pb2_grpc.add_EvaluationServicer_to_server(
      servicer, server)
  server.add_secure_port("[::]:{}".format(port), server_creds)
  servers.append(server)
  server.start()
  print("Start server {}".format(FLAGS.server_id))

  # prevent the main thread from exiting
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    for server in servers:
      server.stop(0) 
開發者ID:utra-robosoccer,項目名稱:soccer-matlab,代碼行數:26,代碼來源:ars_server.py

示例2: run_purerpc_service_in_process

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def run_purerpc_service_in_process(service):
    def target_fn():
        import purerpc
        server = purerpc.Server(port=0)
        server.add_service(service)
        socket = server._create_socket_and_listen()
        yield socket.getsockname()[1]

        async def sleep_10_seconds_then_die():
            await anyio.sleep(20)
            raise ValueError

        async def main():
            async with anyio.create_task_group() as tg:
                await tg.spawn(server._run_async_server, socket)
                await tg.spawn(sleep_10_seconds_then_die)
        # import cProfile
        anyio.run(server._run_async_server, socket)
        # cProfile.runctx("anyio.run(main)", globals(), locals(), sort="tottime")
    return _run_context_manager_generator_in_process(target_fn) 
開發者ID:standy66,項目名稱:purerpc,代碼行數:22,代碼來源:test_utils.py

示例3: _get_tls_cert_and_key

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def _get_tls_cert_and_key():
  """Get the TLS cert from instance metadata."""
  # TODO(ochang): Implement a fake metadata server for testing.
  local_cert_location = environment.get_value('UNTRUSTED_TLS_CERT_FOR_TESTING')
  local_key_location = environment.get_value('UNTRUSTED_TLS_KEY_FOR_TESTING')

  if local_cert_location and local_key_location:
    with open(local_cert_location, 'rb') as f:
      cert_contents = f.read()

    with open(local_key_location, 'rb') as f:
      key_contents = f.read()

    return cert_contents, key_contents

  cert_contents = compute_metadata.get('instance/attributes/tls-cert').encode()
  key_contents = compute_metadata.get('instance/attributes/tls-key').encode()
  return cert_contents, key_contents 
開發者ID:google,項目名稱:clusterfuzz,代碼行數:20,代碼來源:untrusted.py

示例4: GetResults

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def GetResults(self, request, context):
        logger.debug("server: get_results")
        if request.comp_id not in self.results:
            message = 'unknown computation id {}'.format(request.comp_id)
            return hetr_pb2.GetResultsReply(status=False, message=message)

        try:
            pb_results = []
            for r in self.results[request.comp_id]:
                pb_val = hetr_pb2.Value()
                if is_scalar_type(r):
                    assign_scalar(pb_val.scalar, r)
                else:
                    pb_val.tensor.CopyFrom(tensor_to_protobuf(r))
                pb_results.append(pb_val)
            return hetr_pb2.GetResultsReply(status=True, results=pb_results)
        except Exception:
            return hetr_pb2.GetResultsReply(status=False, message=traceback.format_exc()) 
開發者ID:NervanaSystems,項目名稱:ngraph-python,代碼行數:20,代碼來源:hetr_server.py

示例5: __init__

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def __init__(self, port=50055, model_status=0, model_output=""):
        self.port = port
        self.model_status = model_status
        self.model_output = model_output
        log.info("Initializing GRPC Server", port=port)
        self.thread_pool = futures.ThreadPoolExecutor(max_workers=10)
        self.server = grpc.server(self.thread_pool)
        self.django_initialized = False
        self.django_apps = []

        server_key = open(SERVER_KEY, "r").read()
        server_cert = open(SERVER_CERT, "r").read()
        server_ca = open(SERVER_CA, "r").read()

        self.credentials = grpc.ssl_server_credentials(
            [(server_key, server_cert)], server_ca, False
        )

        self.delayed_shutdown_timer = None
        self.exit_event = threading.Event()

        self.services = [] 
開發者ID:open-cloud,項目名稱:xos,代碼行數:24,代碼來源:grpc_server.py

示例6: start

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def start():
    if environ.get('DEBUGGING'):
        ptvsd.enable_attach(address=(
            '127.0.0.1', int(environ.get('DEBUG_PORT'))))
        print(ATTACH_DEBUGGER_EVENT)
        t = Timer(int(environ.get("debugger_wait_time", 30)), _handle_detached)
        t.start()
        ptvsd.wait_for_attach()
        t.cancel()
    logger.debug('Starting grpc server..')
    server = grpc.server(ThreadPoolExecutor(max_workers=1))
    p = server.add_insecure_port('127.0.0.1:0')
    handler = handlers.GrpcServiceHandler(server)
    spg.add_RunnerServicer_to_server(handler, server)
    logger.info('Listening on port:{}'.format(p))
    server.start()
    t = threading.Thread(name="listener", target=handler.wait_for_kill_event)
    t.start()
    t.join()
    os._exit(0) 
開發者ID:getgauge,項目名稱:gauge-python,代碼行數:22,代碼來源:start.py

示例7: serve

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def serve(models, max_workers: int=1, port: int=9000):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers),
                         options=[('grpc.max_send_message_length', GIGABYTE),
                                  ('grpc.max_receive_message_length', GIGABYTE)
                                  ])
    prediction_service_pb2_grpc.add_PredictionServiceServicer_to_server(
        PredictionServiceServicer(models=models), server)
    model_service_pb2_grpc.add_ModelServiceServicer_to_server(
        ModelServiceServicer(models=models), server)
    server.add_insecure_port('[::]:{}'.format(port))
    server.start()
    logger.info("gRPC server listens on port {port} and will be "
                "serving models: {models}".format(port=port,
                                                  models=list(models.keys())))
    try:
        while True:
            if GLOBAL_CONFIG['file_system_poll_wait_seconds'] > 0:
                time.sleep(GLOBAL_CONFIG['file_system_poll_wait_seconds'])
                for model in models:
                    models[model].update()
            else:
                time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
        sys.exit(0) 
開發者ID:openvinotoolkit,項目名稱:model_server,代碼行數:27,代碼來源:start.py

示例8: main

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def main(listen_addrs=['127.0.0.1:9901']):
    s = create_server(listen_addrs)
    print("Server created on", listen_addrs)
    s.start()
    print("Server started")
    import signal
    old1 = signal.signal(signal.SIGINT, signal_handler)
    old2 = signal.signal(signal.SIGTERM, signal_handler)
    import time
    # signal.pause is not valid in windows
    try:
        while True:
            time.sleep(3600 * 24)
    except QuitException:
        print("Quit server")
        shutdown_event = s.stop(5)
        shutdown_event.wait()
    finally:
        signal.signal(signal.SIGINT, old1)
        signal.signal(signal.SIGTERM, old2) 
開發者ID:hubo1016,項目名稱:aiogrpc,代碼行數:22,代碼來源:server.py

示例9: __init__

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def __init__(self, worker_id=0, base_port=5005, timeout_wait=30):
        """
        Python side of the grpc communication. Python is the server and Unity the client


        :int base_port: Baseline port number to connect to Unity environment over. worker_id increments over this.
        :int worker_id: Offset from base_port. Used for training multiple environments simultaneously.
        :int timeout_wait: Timeout (in seconds) to wait for a response before exiting.
        """
        super().__init__(worker_id, base_port)
        self.port = base_port + worker_id
        self.worker_id = worker_id
        self.timeout_wait = timeout_wait
        self.server = None
        self.unity_to_external = None
        self.is_open = False
        self.create_server() 
開發者ID:StepNeverStop,項目名稱:RLs,代碼行數:19,代碼來源:rpc_communicator.py

示例10: create_server

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def create_server(self):
        """
        Creates the GRPC server.
        """
        self.check_port(self.port)

        try:
            # Establish communication grpc
            self.server = grpc.server(ThreadPoolExecutor(max_workers=10))
            self.unity_to_external = UnityToExternalServicerImplementation()
            add_UnityToExternalProtoServicer_to_server(
                self.unity_to_external, self.server
            )
            # Using unspecified address, which means that grpc is communicating on all IPs
            # This is so that the docker container can connect.
            self.server.add_insecure_port("[::]:" + str(self.port))
            self.server.start()
            self.is_open = True
        except Exception:
            raise UnityWorkerInUseException(self.worker_id) 
開發者ID:StepNeverStop,項目名稱:RLs,代碼行數:22,代碼來源:rpc_communicator.py

示例11: serve

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    metric_interceptor = MetricInterceptor()
    logging_interceptor = LoggingInterceptor()
    server = intercept_server(server, metric_interceptor, logging_interceptor)
    users_service.add_UsersServicer_to_server(UsersService(), server)

    # read in key and certificate
    with open(os.path.join(os.path.split(__file__)[0], 'server.key')) as f:
        private_key = f.read().encode()
    with open(os.path.join(os.path.split(__file__)[0], 'server.crt')) as f:
        certificate_chain = f.read().encode()
    # create server credentials
    server_creds = grpc.ssl_server_credentials(
        ((private_key, certificate_chain,),))
    server.add_secure_port('localhost:50051', server_creds)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0) 
開發者ID:amitsaha,項目名稱:python-grpc-demo,代碼行數:24,代碼來源:server.py

示例12: main

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def main():
    print('Starting server. Listening on port 50051.')
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    kcli_pb2_grpc.add_KcliServicer_to_server(KcliServicer(), server)
    kcli_pb2_grpc.add_KconfigServicer_to_server(KconfigServicer(), server)
    try:
        from grpc_reflection.v1alpha import reflection
        SERVICE_NAMES = (
            kcli_pb2.DESCRIPTOR.services_by_name['Kcli'].full_name,
            kcli_pb2.DESCRIPTOR.services_by_name['Kconfig'].full_name,
            reflection.SERVICE_NAME,
        )
    except:
        pass
    reflection.enable_server_reflection(SERVICE_NAMES, server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(86400)
    except KeyboardInterrupt:
        server.stop(0) 
開發者ID:karmab,項目名稱:kcli,代碼行數:24,代碼來源:server.py

示例13: GetClientConfig

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def GetClientConfig(self, request, context):
        """Return parameters to the client to set up channel options as desired by the server.
        """
        clientCFG = self.CFG['CLIENT_GRPC']
        push_max_nbytes = clientCFG['push_max_nbytes']
        enable_compression = clientCFG['enable_compression']
        optimization_target = clientCFG['optimization_target']

        err = hangar_service_pb2.ErrorProto(code=0, message='OK')
        reply = hangar_service_pb2.GetClientConfigReply(error=err)
        reply.config['push_max_nbytes'] = push_max_nbytes
        reply.config['enable_compression'] = enable_compression
        reply.config['optimization_target'] = optimization_target
        return reply

    # -------------------- Branch Record -------------------------------------- 
開發者ID:tensorwerk,項目名稱:hangar-py,代碼行數:18,代碼來源:server.py

示例14: PushSchema

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def PushSchema(self, request, context):
        """Add a new schema byte specification record.

        Will not overwrite a schema hash which already exists on the server.
        """
        schema_hash = request.rec.digest
        schema_val = request.rec.blob

        digest = self.CW.schema(schema_hash, schema_val)
        if not digest:
            print(f'exists: {schema_val}')
            msg = f'SCHEMA: {schema_hash} ALREADY EXISTS ON SERVER'
            context.set_details(msg)
            context.set_code(grpc.StatusCode.ALREADY_EXISTS)
            err = hangar_service_pb2.ErrorProto(code=6, message=msg)
        else:
            print(f'created new: {schema_val}')
            err = hangar_service_pb2.ErrorProto(code=0, message='OK')
        reply = hangar_service_pb2.PushSchemaReply(error=err)
        return reply

    # ---------------------------- Data --------------------------------------- 
開發者ID:tensorwerk,項目名稱:hangar-py,代碼行數:24,代碼來源:server.py

示例15: PushFindMissingCommits

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import server [as 別名]
def PushFindMissingCommits(self, request, context):
        """Determine commit digests existing on the client which are not present on the server.
        """
        c_branch_name = request.branch.name
        c_head_commit = request.branch.commit
        c_ordered_commits = request.commits

        s_commits = commiting.list_all_commits(self.env.refenv)
        s_orderset = set(s_commits)
        c_orderset = set(c_ordered_commits)
        s_missing = list(c_orderset.difference(s_orderset))  # only difference to FetchFindMissingCommits

        err = hangar_service_pb2.ErrorProto(code=0, message='OK')
        if len(s_missing) == 0:
            brch = hangar_service_pb2.BranchRecord(name=c_branch_name, commit=c_head_commit)
            reply = hangar_service_pb2.FindMissingCommitsReply(branch=brch, error=err)
        else:
            brch = hangar_service_pb2.BranchRecord(name=c_branch_name, commit=c_head_commit)
            reply = hangar_service_pb2.FindMissingCommitsReply(branch=brch, error=err)
            reply.commits.extend(s_missing)

        return reply 
開發者ID:tensorwerk,項目名稱:hangar-py,代碼行數:24,代碼來源:server.py


注:本文中的grpc.server方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。