Я сгенерировал два файла с grpc в python (), теперь я хотел бы сделать клиент, который использует методы grpc. Первый шаг - создать заглушку:
grpcChannel = grpc.insecure_channel('https://.....')
stub = garden_pb2_grpc.GardenServiceStub(grpcChannel)
Теперь я хочу использовать метод моей заглушки, поэтому я делаю так:
feature = stub.Create(test)
Проблема в том, что я надеваюне знаю, как создать объект. Поэтому я делаю это так:
test = garden_pb2.CreateRequest()
это не работает, потому что у меня нет аргументов в моем createrequest, но я не знаю, где их найти (ну, в моем файле grpc, но яне понимаю)Как я могу создать свой объект и как я могу увидеть аргументы, которые ему нужны? Потому что в файле есть две одинаковые функции, и я не знаю разницы между ними.
Мои файлы:
garden_p2_grpc.py:
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import garden_pb2 as garden__pb2
class GardenServiceStub(object):
"""Service to manage list of todo tasks
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Create = channel.unary_unary(
'/proto.GardenService/Create',
request_serializer=garden__pb2.CreateRequest.SerializeToString,
response_deserializer=garden__pb2.CreateResponse.FromString,
)
self.Read = channel.unary_unary(
'/proto.GardenService/Read',
request_serializer=garden__pb2.ReadRequest.SerializeToString,
response_deserializer=garden__pb2.ReadResponse.FromString,
)
self.Update = channel.unary_unary(
'/proto.GardenService/Update',
request_serializer=garden__pb2.UpdateRequest.SerializeToString,
response_deserializer=garden__pb2.UpdateResponse.FromString,
)
self.Delete = channel.unary_unary(
'/proto.GardenService/Delete',
request_serializer=garden__pb2.DeleteRequest.SerializeToString,
response_deserializer=garden__pb2.DeleteResponse.FromString,
)
self.ReadAll = channel.unary_unary(
'/proto.GardenService/ReadAll',
request_serializer=garden__pb2.ReadAllRequest.SerializeToString,
response_deserializer=garden__pb2.ReadAllResponse.FromString,
)
class GardenServiceServicer(object):
"""Service to manage list of todo tasks
"""
def Create(self, request, context):
"""Create new todo task
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Read(self, request, context):
"""Read todo task
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Update(self, request, context):
"""Update todo task
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Delete(self, request, context):
"""Delete todo task
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ReadAll(self, request, context):
"""Read all todo tasks
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_GardenServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'Create': grpc.unary_unary_rpc_method_handler(
servicer.Create,
request_deserializer=garden__pb2.CreateRequest.FromString,
response_serializer=garden__pb2.CreateResponse.SerializeToString,
),
'Read': grpc.unary_unary_rpc_method_handler(
servicer.Read,
request_deserializer=garden__pb2.ReadRequest.FromString,
response_serializer=garden__pb2.ReadResponse.SerializeToString,
),
'Update': grpc.unary_unary_rpc_method_handler(
servicer.Update,
request_deserializer=garden__pb2.UpdateRequest.FromString,
response_serializer=garden__pb2.UpdateResponse.SerializeToString,
),
'Delete': grpc.unary_unary_rpc_method_handler(
servicer.Delete,
request_deserializer=garden__pb2.DeleteRequest.FromString,
response_serializer=garden__pb2.DeleteResponse.SerializeToString,
),
'ReadAll': grpc.unary_unary_rpc_method_handler(
servicer.ReadAll,
request_deserializer=garden__pb2.ReadAllRequest.FromString,
response_serializer=garden__pb2.ReadAllResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'proto.GardenService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
```
My client:
```
# example_consumer.py
import pika, os, time
import grpc
import garden_pb2_grpc
import garden_pb2
# Access the CLODUAMQP_URL environment variable and parse it (fallback to localhost)
url = os.environ.get('CLOUDAMQP_URL', 'amqp://layana:layana321@localhost:5672')
params = pika.URLParameters(url)
connection = pika.BlockingConnection(params)
channel = connection.channel() # start a channel
channel.queue_declare(queue='garden') # Declare a queue
grpcChannel = grpc.insecure_channel('https://de.eu')
stub = garden_pb2_grpc.GardenServiceStub(grpcChannel)
test = garden_pb2.CreateRequest() #how can i create it ?
def garden_process_function(msg):
print("Received " + str(msg))
print("This function can do something")
time.sleep(1) # delays for 5 seconds
feature = stub.Create(test)
return;
# create a function which is called on incoming messages
def callback(ch, method, properties, body):
garden_process_function(body)
class Server(object):
@staticmethod
def receiveMsg():
# set up subscription on the queue
channel.basic_consume('garden',
callback,
auto_ack=True)
# start consuming (blocks)
channel.start_consuming()
connection.close()
class App(object):
@staticmethod
def run():
print('Running...')
if __name__ == '__main__':
App.run()
Server.receiveMsg()
```
```
How can I create my object and how can I see the arguments it needs? Because there are two times the same function in the file and I don't know the difference between the two.