python实现grpc发送文件_GRPC以及python实现

本文介绍了gRPC的高性能、开放源码的RPC框架特性,并通过一个Python示例展示了如何使用gRPC进行服务定义、客户端和服务器端的实现。内容包括gRPC的优势、工作原理、安装步骤、Python gRPC基本用法,以及如何通过protobuf定义服务并实现简单的RPC调用。最后,文章演示了如何修改.proto文件以添加新的服务方法,并在客户端和服务器端进行调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GRPC简介

A high-performance, open-source universal RPC framework --官网

rpc通信

RPC(remote procedure call 远程过程调用)

是什么:提供一套应用程序之间可以通信的机制,使用C/S模型,Client进程调用Server进程提供的接口就像是调用本地函数一样。

为什么:相比较restful API的优势:

(1)gRPC都使用http底层传输协议建立C/S通信模型,但gRPC使用http2

(2)gRPC可以通过protobuf来定义由严格约束条件的接口,在提供公共API服务时,如果不希望client端给我们传递乱七八糟的数据,就可以定义输入的约束。

(3)gRPC通过protobuf将数据转化为二进制编码,减少传输数据量来提高传输性能。在需要服务器传递大量数据的场景下效率更高。

(4)gRPC通过http2.0可以方便的使用streaming模式做流式通信(通常的流式数据:视频流)

怎么用:grpc官网的一个简单Python栗子

(1)在.proto文件中定义服务。

(2)使用协议缓冲区编译器生成服务器和客户端代码。

(3)使用Python gRPC API为您的服务编写一个简单的客户端和服务器。

安装:

$ python -m pip install grpcio # 安装gprc

$ python -m pip install grpcio-tools #安装grpc-tools

Python grpc tutorial:The example code for this tutorial is in grpc/grpc/examples/python/route_guide.

QuitStart Python gRPC

下载代码

$ git clone -b v1.27.0 https://github.com/grpc/grpc

$ cd grpc/examples/python/helloworld

运行gRPC应用:用两个终端窗口一个运行Server进程,一个运行Client进程

$ python greeter_server.py # 启动Server

$ python greeter_client.py # 在另外一个terminal启动client

Server端代码

"""The Python implementation of the GRPC helloworld.Greeter server."""

from concurrent import futures

import logging

import grpc

import helloworld_pb2

import helloworld_pb2_grpc

class Greeter(helloworld_pb2_grpc.GreeterServicer):

# 自定义对外开放的API接口

def SayHello(self, request, context):

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

def serve():

# 使用ThreadPool并发处理Server任务

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

# 把对应的Greeter任务添加到rpc server中

helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)

# 这里使用的非安全接口,gRPC支持TLS/SSL安全连接,以及各种鉴权机制

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

server.start()

server.wait_for_termination()

if __name__ == '__main__':

logging.basicConfig()

serve()

Client端代码

"""The Python implementation of the GRPC helloworld.Greeter client."""

from __future__ import print_function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值