协议文件test_model.proto
//Filename: test_model.proto
syntax="proto3";
service model{ //model:表示服务的名称
rpc test_show(hdc_Request) returns (hdc_Response){}
//test_show:表示函数名,hdc_Request:表示输入参数,hdc_Response:表示输出参数
}
message hdc_Request{ //表示输入参数包含3个变量
string index=1;
string name=2;
int64 age=3;
}
message hdc_Response{ //表示输出参数返回两个变量参数
string stu_class=1;
int64 grade=2;
}
1、再协议文件路径下cmd命令执行:python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. hdc_model.proto
生成如下两个文件:
hdc_model_pb2.py
hdc_model_pb2_grpc.py
服务端文件hdc_model_server.py
#coding=utf-8
import grpc
import time
from concurrent import futures
import hdc_model_pb2
import hdc_model_pb2_grpc
_ONE_DAT_IN_SECONDES=60 * 60 *24
_HOST='localhost'
_PORT='6060'
#继承(hdc_model_pb2_grpc.modelServicer类
class model(hdc_model_pb2_grpc.modelServicer):
###随意定义封装好的函数###
def search_student_class(self,index):
if index == '201801':
student_class='201801'
return student_class
else:
return '0'
def search_student_grade(self,name,age):
if name == 'hdc' and age == 30:
student_grade= 30
return student_grade
else:
return 1
###重写继承的父类的方法###
###真正重要的输出函数###
#该函数名即为hdc_model_pb2_grpc中服务类里的函数{class modelServicer(object)的函数test_show}
def test_show(self,request,context): #此函数格式固定写法(self,request,context)
#先获取请求传来的参数
index = request.index #request.index就是输入参数index变量,以此方式获取输入参数的变量值
name = request.name #就是hdc_model.proto中定义的变量名定义的message hdc_Request中的输入的参数变量名
age = request.age
#获取想要输出的参数变量的值
student_class=self.search_student_class(index)
student_grade=self.search_student_grade(name,age)
print('tansfer')
#name_pb2.输出参数(输出参数变量=赋值)
"""
stu_class和grade就是协议文件hdc_model.proto中定义的变量名
message hdc_Response{ //表示输出参数包含2个变量
string stu_class=1;
int64 grade=2;
}
"""
#返回响应结果,调用hdc_model_pb2的响应请求方法hdc_Response(),并传入由请求传递来的参数
#只要客户端调用了就返回该结果
return hdc_model_pb2.hdc_Response(stu_class=student_class,grade=student_grade)
def server():
#标准格式,无须改动
grpcServer=grpc.server(futures.ThreadPoolExecutor(max_workers=10)) #max_workers表示最大连接数,这里设置为10
hdc_model_pb2_grpc.add_modelServicer_to_server(model(),grpcServer) #name_pb2_groc.add_modelServicer_to_server(上述定义的类对象model(),上述定义的grpcServer)
grpcServer.add_insecure_port(_HOST+ ":" +_PORT)
grpcServer.start()
try:
while True:
time.sleep(_ONE_DAT_IN_SECONDES)
except KeyboardInterrupt:
grpcServer.stop(0)
if __name__ == '__main__':
server()
客户端文件hdc_model_client.py
#coding=utf-8
import grpc
import hdc_model_pb2
import hdc_model_pb2_grpc
_HOST='localhost'
_PORT='6060'
def run():
###连接rpc服务器,insecure(不安全的)###
channel=grpc.insecure_channel(_HOST+":"+_PORT)
###调用rpc服务###
stub=hdc_model_pb2_grpc.modelStub(channel=channel)
#调用服务端里里的方法test_show(),并传递请求需要的参数,获取服务器端返回的结果
response=stub.test_show(hdc_model_pb2.hdc_Request(index='201801',name='hdc',age=30))
print("received: "+ response.stu_class)
print("received: "+ str(response.grade))
if __name__ == '__main__':
run()
hdc_model_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import hdc_model_pb2 as hdc__model__pb2
class modelStub(object):
"""model:表示服务的名称
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.test_show = channel.unary_unary(
'/model/test_show',
request_serializer=hdc__model__pb2.hdc_Request.SerializeToString,
response_deserializer=hdc__model__pb2.hdc_Response.FromString,
)
class modelServicer(object):
"""model:表示服务的名称
"""
def test_show(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_modelServicer_to_server(servicer, server):
rpc_method_handlers = {
'test_show': grpc.unary_unary_rpc_method_handler(
servicer.test_show,
request_deserializer=hdc__model__pb2.hdc_Request.FromString,
response_serializer=hdc__model__pb2.hdc_Response.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'model', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class model(object):
"""model:表示服务的名称
"""
@staticmethod
def test_show(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/model/test_show',
hdc__model__pb2.hdc_Request.SerializeToString,
hdc__model__pb2.hdc_Response.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: hdc_model.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='hdc_model.proto',
package='',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x0fhdc_model.proto\"7\n\x0bhdc_Request\x12\r\n\x05index\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0b\n\x03\x61ge\x18\x03 \x01(\x03\"0\n\x0chdc_Response\x12\x11\n\tstu_class\x18\x01 \x01(\t\x12\r\n\x05grade\x18\x02 \x01(\x03\x32\x33\n\x05model\x12*\n\ttest_show\x12\x0c.hdc_Request\x1a\r.hdc_Response\"\x00\x62\x06proto3'
)
_HDC_REQUEST = _descriptor.Descriptor(
name='hdc_Request',
full_name='hdc_Request',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='index', full_name='hdc_Request.index', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='name', full_name='hdc_Request.name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='age', full_name='hdc_Request.age', index=2,
number=3, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=19,
serialized_end=74,
)
_HDC_RESPONSE = _descriptor.Descriptor(
name='hdc_Response',
full_name='hdc_Response',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='stu_class', full_name='hdc_Response.stu_class', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='grade', full_name='hdc_Response.grade', index=1,
number=2, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=76,
serialized_end=124,
)
DESCRIPTOR.message_types_by_name['hdc_Request'] = _HDC_REQUEST
DESCRIPTOR.message_types_by_name['hdc_Response'] = _HDC_RESPONSE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
hdc_Request = _reflection.GeneratedProtocolMessageType('hdc_Request', (_message.Message,), {
'DESCRIPTOR' : _HDC_REQUEST,
'__module__' : 'hdc_model_pb2'
# @@protoc_insertion_point(class_scope:hdc_Request)
})
_sym_db.RegisterMessage(hdc_Request)
hdc_Response = _reflection.GeneratedProtocolMessageType('hdc_Response', (_message.Message,), {
'DESCRIPTOR' : _HDC_RESPONSE,
'__module__' : 'hdc_model_pb2'
# @@protoc_insertion_point(class_scope:hdc_Response)
})
_sym_db.RegisterMessage(hdc_Response)
_MODEL = _descriptor.ServiceDescriptor(
name='model',
full_name='model',
file=DESCRIPTOR,
index=0,
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_start=126,
serialized_end=177,
methods=[
_descriptor.MethodDescriptor(
name='test_show',
full_name='model.test_show',
index=0,
containing_service=None,
input_type=_HDC_REQUEST,
output_type=_HDC_RESPONSE,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
])
_sym_db.RegisterServiceDescriptor(_MODEL)
DESCRIPTOR.services_by_name['model'] = _MODEL
# @@protoc_insertion_point(module_scope)