0

我刚刚掌握了 grpc 并尝试构建一个自定义客户端-服务器过程,其中客户端发送一个 id 和一个与 id 对应的名称。

这是 custom.proto 文件:

 syntax = "proto3" ;

// Interface exported by the server
service Detail {
   rpc GetName(idx) returns (namex) {}
}

message idx {
   int32 id = 1;
}

message namex{
   int32 id = 1;
   string name = 2;
}

从此原型文件 custom_pb2 和 custom_pb2_grpc.py 生成。

这是 custom_db.json

[{"id": 0, "name":"kiran"},
 {"id":1, "name":"kirthana"},
 {"id":2, "name":"kishore"}
]

这是 custom_resources.py

import json

import custom_pb2


def read_custom_database():
    ''' Reads the custom database I created.'''
    names_list = []
    with open("custom_db.json") as custom_db_file:
        for item in json.load(custom_db_file):
            itemx = custom_pb2.namex(id=item["id"], name=item["name"])
            names_list.append(itemx)
    return names_list

这是 custom_server.py

import custom_pb2_grpc
import custom_resources
import time

_ONE_DAT_IN_SECONDS = 60*60*24

def get_name(custom_db,idx):
    '''Returns name of a given id or none'''
    for namex in custom_db:
        if namex.id == idx:
            return namex.name
    return None


class DetailServicer(custom_pb2_grpc.DetailServicer):
    """Provides methods that implements the custom server."""

    def __init__(self):
        self.db = custom_resources.read_custom_database()

    def GetName(self, request, context):
        name = get_name(self.db, request)
        if name is None:
            return "Not Found"
        else:
            return name


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    custom_pb2_grpc.add_DetailServicer_to_server(DetailServicer(), server)
    server.add_insecure_port('[::]:12345')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAT_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == '__main__':
    serve()

这是 custom_client.py

from __future__ import print_function

import random

import grpc

import custom_pb2
import custom_pb2_grpc
import custom_resources


def custom_get_one_name(stub, idx):
    name = stub.GetName(idx)
    print("Feater called with id %d returned: %s" %(idx,name))
    return

def custom_get_names(stub):
    custom_get_one_name(stub,2)
    custom_get_one_name(stub,1)


def run():
    with grpc.insecure_channel('localhost:12345') as channel:
        stub = custom_pb2_grpc.DetailStub(channel)
        custom_get_names(stub)

if __name__ == '__main__':
    run()

我得到的确切错误消息是:

No handlers could be found for logger "grpc._common"
Traceback (most recent call last):
  File "custom_client.py", line 30, in <module>
    run()
  File "custom_client.py", line 27, in run
    custom_get_names(stub)
  File "custom_client.py", line 19, in custom_get_names
    custom_get_one_name(stub,2)
  File "custom_client.py", line 13, in custom_get_one_name
    name = stub.GetName(idx)
  File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 513, in __call__
    state, call, = self._blocking(request, timeout, metadata, credentials)
  File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 500, in _blocking
    raise rendezvous
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
    status = StatusCode.INTERNAL
    details = "Exception serializing request!"
    debug_error_string = "None"

谢谢您的帮助。

4

1 回答 1

0

您正在尝试传递一个整数作为请求custom_get_one_name(stub,2),其中需要协议缓冲区类型idx的消息。您应该创建一条idx消息并传递它,而不是像:

custom_get_one_name(stub, custom_pb2_grpc.idx(id=2))
于 2018-08-14T15:12:20.563 回答