File: user.proto syntax = "proto3";
package user;
// Define the User service
service UserService {
// RPC method to get user details by user_id
rpc GetUser (UserRequest) returns (UserResponse);
}
// Request message
message UserRequest {
int32 user_id = 1;
}
// Response message
message UserResponse {
int32 user_id = 1;
string name = 2;
string email = 3;
bool is_active = 4;
}
Step 2: Generate gRPC Code> python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. user.proto
This will generate two files: user_pb2.py – Contains the message classes.user_pb2_grpc.py – Contains the service class and stub.
| File: server.py import grpc
from concurrent import futures
import time
import user_pb2
import user_pb2_grpc
# Create a class to define the server functions
class UserServiceServicer(user_pb2_grpc.UserServiceServicer):
def GetUser(self, request, context):
print(f"Received request for user_id: {request.user_id}")
# Dummy data for demonstration
users = {
1: {"name": "Alice", "email": "alice@example.com", "is_active": True},
2: {"name": "Bob", "email": "bob@example.com", "is_active": False},
}
user_data = users.get(request.user_id, {"name": "Unknown", "email": "", "is_active": False})
# Create a response
return user_pb2.UserResponse(
user_id=request.user_id,
name=user_data["name"],
email=user_data["email"],
is_active=user_data["is_active"]
)
# Create and start the gRPC server
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
user_pb2_grpc.add_UserServiceServicer_to_server(UserServiceServicer(), server)
server.add_insecure_port("[::]:50051")
server.start()
print("Server started on port 50051")
try:
while True:
time.sleep(86400) # Keep server running for 1 day
except KeyboardInterrupt:
server.stop(0)
if __name__ == "__main__":
serve()
| import grpc
import user_pb2
import user_pb2_grpc
def run():
# Connect to the server
with grpc.insecure_channel("localhost:50051") as channel:
stub = user_pb2_grpc.UserServiceStub(channel)
# Create a request
user_id = int(input("Enter user ID: "))
request = user_pb2.UserRequest(user_id=user_id)
# Send the request and get the response
try:
response = stub.GetUser(request)
print(f"User ID: {response.user_id}")
print(f"Name: {response.name}")
print(f"Email: {response.email}")
print(f"Active: {response.is_active}")
except grpc.RpcError as e:
print(f"Error: {e.details()}")
if __name__ == "__main__":
run()
|