python实现grpc发送文件_Python版gRPC入门实验

什么是RPCRPC(Remote Procedure Call Protocol)-- 远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络协议的协议。RPC协议假定某些传输协议的存在,如TCP或UDP,为通信程序之间携带信息数据。在OSI网络通信模型中,RPC跨越了传输层和应用层。RPC使得开发包括网络分布式多程序在内的应用程序更加容易。

什么是gRPCgRPC 是Google开源的一款高性能的 RPC 框架,它基于 ProtoBuf 序列化协议进行开发,支持多种开发语言(Golang、Python、Java、C/C++等)。gRPC 提供了一种简单的方法来定义服务,同时客户端可以充分利用 HTTP/2 stream 的特性,从而有助于节省带宽、降低 TCP 的连接次数、节省CPU的使用等。

本文参考官方文档[grpc.html],以及gRPC的GitHub开源项目grpc/grpc。并通过一个小demo展示框架用法。

安装gRPC及gRPC工具

pip install grpcio

pip install grpcio-tools

grpcio-tools包含了protobuf的编辑工具 protoc,用来根据 .proto 服务定义生成服务器端和客户端代码。

自定义 gRPC 接口

假定这里我们需要定义一个数据接收服务Receiver,用来接收客户端传递给服务器端的数据。

syntax = "proto3";

import "google/protobuf/struct.proto";

// 服务定义

service Receiver {

rpc receive (Event) returns (Reply) {}

}

// 接收消息定义

message Event {

string appid = 1;

int32 xwhen = 2;

string xwho = 3;

string xwhat = 4;

google.protobuf.Struct xcontext = 5;

}

// 返回消息定义

message Reply {

int32 status = 1;

string message = 2;

}

编译 proto 文件生成服务接口

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./receiver.proto

这里会生成两个python文件:

receiver_pb2.py

receiver_pb2_grpc.py

编写Server端代码

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

import grpc

import receiver_pb2

import receiver_pb2_grpc

import time

from concurrent import futures

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class Receiver(receiver_pb2_grpc.ReceiverServicer):

# 重写父类方法,返回消息

def receive(self, request, context):

print('request:', request)

return receiver_pb2.Reply(message='Hello,%s!' % request.xwho)

if __name__ == '__main__':

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

receiver_pb2_grpc.add_ReceiverServicer_to_server(Receiver(), server)

server.add_insecure_port('[::]:50051')

server.start()

print('server start...')

try:

while True:

time.sleep(_ONE_DAY_IN_SECONDS)

except KeyboardInterrupt:

server.stop(0)

编写client端代码

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

import grpc

import receiver_pb2

import receiver_pb2_grpc

from google.protobuf import struct_pb2

def run():

channel = grpc.insecure_channel('localhost:50051')

stub = receiver_pb2_grpc.ReceiverStub(channel)

# 自定义struct结构

struct = struct_pb2.Struct()

struct['idfa'] = 'idfa1'

struct['amount'] = 123

response = stub.receive(receiver_pb2.Event(xwhat='install', appid='fuckgod', xwhen=123, xwho='jerry', xcontext=struct))

print("client status: %s received: %s" % (response.status, response.message))

if __name__ == '__main__':

run()

测试流程

(1)启动server:python server.py &

(2)运行client.py发送消息

server输出:

server start...

request:

appid: "fuckgod"

xwhen: 123

xwho: "jerry"

xwhat: "install"

xcontext {

fields {

key: "amount"

value {

number_value: 123.0

}

}

fields {

key: "idfa"

value {

string_value: "idfa1"

}

}

}

client输出:

client status: 0 received: Hello, jerry!

表示测试成功。

参考:grpc /​grpc.iogrpc/grpc​github.comgrpc/grpc​github.com

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、付费专栏及课程。

余额充值