本文整理汇总了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)
示例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)
示例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
示例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())
示例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 = []
示例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)
示例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)
示例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)
示例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()
示例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)
示例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)
示例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)
示例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 --------------------------------------
示例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 ---------------------------------------
示例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