python grpc_记python使用grpc

本文介绍了如何使用gRPC和ProtoBuf在Python中创建一个跨语言通信的示例。gRPC是一个基于HTTP/2的RPC框架,ProtoBuf作为数据序列化工具。通过编写ProtoBuf接口定义文件,编译生成Python服务端和客户端所需文件,然后实现服务端和客户端的代码,完成数据的发送和接收。示例中展示了服务端如何处理请求并返回响应,以及客户端如何调用服务端接口并打印响应信息。
摘要由CSDN通过智能技术生成

using grpc in Python

gRPC是基于http/2的RPC框架,使用ProtoBuf作为底层数据序列化。Nginx服务器2018年3月17日引入gRPC支持。

gRPC 是用来实现跨语言通信的。比如在你的某个功能里需要用的同事写的接口,而你们俩又不是同一种语言。此时有两种方案,一是使用.so 文件;另一种则是使用 RPC 框架。

创建一个grpc_demo项目,结构如下

grpc_demo/

├── client

│ └── client.py

├── example

│ └── data.proto

└── server

​ └── server.py

client目录下的client.py实现了客户端用于发送数据并打印接收到server端处理后的数据

server目录下的server.py实现了server端用于接收客户端发送的数据,并对数据进行简单处理后返回给客户端

example包用于编写proto文件并生成data接口

grpc安装

安装gRPC

pip install grpcio

安装 ProtoBuf 相关的 python 依赖库

pip install protobuf

安装 python grpc 的 protobuf 编译工具

pip install grpcio-tools

定义gRPC接口

data.proto文件,service关键字就是定义接口,message定义数据结构

syntax = "proto3";

service Greeter {

rpc SayHello (HelloRequest) returns (HelloReply) {}

}

message HelloRequest {

string name = 1;

string message = 2;

string location = 3;

string ip = 4;

}

message HelloReply {

string name = 1;

string message = 2;

string location = 3;

string ip = 4;

}

编译protobuf生成所需文件(服务端和客户端都需要)

# mkdir gen-py

# python -m grpc_tools.protoc --proto_path=./ --python_out=./gen_py --grpc_python_out=./gen_py ./data.proto

在gen-py目录下生成data_pb2_grpc.py和data_pb2.py两个文件。

生成后完整目录结构:

grpc_demo

├── client

│ └── client.py

├── example

│ ├── data.proto

│ └── gen_py

│ ├── data_pb2_grpc.py

│ └── data_pb2.py

└── server

​ └── server.py

服务端实现

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys

sys.path.append('../example/gen_py')

import grpc

import time

from concurrent import futures

import data_pb2

import data_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

_HOST = "127.0.0.1"

_PORT = "19999"

class HelloWorld(data_pb2_grpc.GreeterServicer):

def SayHello(self, request, context):

print("request: " + str(request))

return data_pb2.HelloReply(message='%s, %s!' % (request.message, request.name))

def server():

grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))

data_pb2_grpc.add_GreeterServicer_to_server(HelloWorld(), grpcServer)

grpcServer.add_insecure_port("{0}:{1}".format(_HOST, _PORT))

grpcServer.start()

try:

while True:

time.sleep(_ONE_DAY_IN_SECONDS)

except KeyboardInterrupt:

grpcServer.stop(0)

if __name__ == '__main__':

server()

客户端实现

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys

sys.path.append("../example/gen_py")

import grpc

import data_pb2

import data_pb2_grpc

_HOST = '127.0.0.1'

_PORT = '19999'

def run():

with grpc.insecure_channel("{0}:{1}".format(_HOST, _PORT)) as channel:

client = data_pb2_grpc.GreeterStub(channel=channel)

response = client.SayHello(data_pb2.HelloRequest(name='you', message='hey guys'))

print("received: " + response.message)

if __name__ == '__main__':

run()

#channel = grpc.insecure_channel("{0}:{1}".format(_HOST, _PORT))

#client = data_pb2_grpc.GreeterStub(channel=channel)

#response = client.SayHello(data_pb2.HelloRequest(name='you', message='hey guys'))

#print("received: " + response.message)

参考:

gRPC 是一种高性能、开源的 RPC 框架,支持多种编程语言。在 Python 中,我们可以使用 gRPC 提供远程过程调用服务。 以下是在 Python使用 gRPC 的基本步骤: 1. 安装 gRPC使用 pip install grpcio 命令安装 gRPC。 2. 定义服务和消息:使用 proto3 编写 .proto 文件,定义服务和消息。 3. 生成代码:使用 protoc 命令生成 Python 代码。 4. 实现服务:在 Python 中实现服务端和客户端。 5. 启动服务:启动服务端程序。 6. 调用服务:在客户端程序中调用远程服务。 以下是一个简单的示例,演示如何在 Python使用 gRPC: 1. 定义服务和消息 ```protobuf syntax = "proto3"; package helloworld; // 定义消息 message HelloRequest { string name = 1; } message HelloReply { string message = 1; } // 定义服务 service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } ``` 2. 生成代码 使用以下命令生成 Python 代码: ```bash python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto ``` 3. 实现服务 在 Python 中实现服务端和客户端。 ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': serve() ``` ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='world')) print("Greeter client received: " + response.message) if __name__ == '__main__': run() ``` 4. 启动服务 在终端中运行以下命令启动服务: ```bash python greeter_server.py ``` 5. 调用服务 在终端中运行以下命令调用服务: ```bash python greeter_client.py ``` 以上是在 Python使用 gRPC 的基本步骤。在生产环境中,我们需要考虑更多的实现细节,例如错误处理、认证和安全等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值