python下用gprc发送和接收文件


CTO要求我们内部模块用grpc通讯,我们需要用python解析bim ifc文件,所以给一位同事写了个python通过grpc发送接收文件的小demo。

grpc不多说了,python安装也不说了,用的版本是3.8.3,操作系统是Windows10,python的IDE用PyCharm。

1、pip安装依赖和工具

pip install grpcio
pip install protobuf
pip install grpcio_tools

2、编写proto

syntax = "proto3";
 
package helloworld;

service FileService {
  rpc Upload(FileRequest) returns (FileReply) {}
}

message FileRequest {
  bytes file = 1;
  string name = 2;
}

message FileReply {
  string msg = 1;
}

3、使用工具生成代码

windows命令行进入proto文件目录下,运行

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

4、编写服务端hello_server.py

from concurrent import futures
import grpc

import helloworld_pb2
import helloworld_pb2_grpc

MAX_MESSAGE_LENGTH = 256 * 1024 * 1024  # 设置grpc最大可接受的文件大小 256M


class FileService(helloworld_pb2_grpc.FileServiceServicer):
    def Upload(self, request, context):
        print("received..")
        file_data = request.file  # 接收到的文件
        file_name = request.name  # 接收到的文件名称
        print(file_name)
        f = open("D:\\" + file_name, "wb")  # 把传来的文件写入本地磁盘
        f.write(file_data)  # 写文件
        f.close()  # 关闭IO

        # 这里我们会处理解析ifc文件,不写了

        return helloworld_pb2.FileReply(msg='ok')


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),
                         options=[('grpc.max_send_message_length', MAX_MESSAGE_LENGTH),
                                  ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH), ])
    helloworld_pb2_grpc.add_FileServiceServicer_to_server(FileService(), server)
    server.add_insecure_port('[::]:50051')
    print('listen on 50051')
    server.start()
    server.wait_for_termination()


if __name__ == '__main__':
    serve()

5、编写客户端hello_server.py

from __future__ import print_function
import grpc

import helloworld_pb2
import helloworld_pb2_grpc


def run():
    with grpc.insecure_channel('localhost:50051') as channel:
        path = 'D:\\yazf.ifc'  # 要发送到服务端的本地ifc文件
        print(path)
        f = open(path, 'rb')  # 读取
        data = f.read()
        f.close()

        # 调用rpc
        stub = helloworld_pb2_grpc.FileServiceStub(channel)
        response = stub.Upload(helloworld_pb2.FileRequest(file=data, name='test.ifc'))

    print("File client received: " + response.msg)


if __name__ == '__main__':
    run()

6、运行测试

先运行hello_server,再运行hello_client,正常情况下目录下会多一个test.ifc文件。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM