Previously, we have demonstrated how to implement a bi-directional gRPC streaming server using python. Once the server implementation is ready we will implement the client.
In order to implement the client we will have to use the same proto file as the server as that acts as a data contract between server and client. Proto file as follows:
syntax = "proto3";
package SamplePackage;
message EntryCreateRequest {
string title = 1;
string code = 2;
string description = 3;
}
message EntryResponse {
string id = 1;
string title = 2;
string code = 3;
string description = 4;
int32 created_on = 6;
}
service SampleService {
rpc createBulkEntries(stream EntryCreateRequest) returns (stream EntryResponse) {}
}
As proto files are not directly readable by python classes, we will convert them to python native class as follows:
python -m grpc_tools.protoc -I./proto --python_out=./proto/ --grpc_python_out=./proto/ ./proto/sample.proto
Let’s define the client to communicate to the gRPC streaming server. The code snippet is fully commented for the ease of understanding.
# import required libraries & proto defn.
import grpc
from proto import sample_pb2_grpc, sample_pb2
# initialize channel to gRPC server
channel = grpc.insecure_channel(target="localhost:50051")
# create service stub
stub = sample_pb2_grpc.SampleServiceStub(channel=channel)
# define request object generator which will yield 15 requests
def entry_request_iterator():
for idx in range(1, 16):
entry_request = sample_pb2.EntryCreateRequest(title=f"Test {idx}", code=f"T{idx}", description=f"Test {idx} description")
yield entry_request
# iterate through response stream and print to console
for entry_response in stub.createBulkEntries(entry_request_iterator()):
print(entry_response)
The above code snippet generates a series of request objects and stream it to the server and fetches the response stream from the server. Output as follows:
$ python client.py
id: "fac2810d-133a-4285-ab62-a8f1cf47c4cb"
title: "Test 1"
code: "T1"
description: "Test 1 description"
created_on: 1628054962
...14 more
Hope the article series will help you to understand bi-directional gRPC streaming with python in step by step approach. We would love to help you to solve any of your issue related to gRPC, you may contact us on LinkedIn: https://www.linkedin.com/in/skallpaul/