grpc官方地址:https://grpc.github.io/grpc/python/index.html

1. grpcio自带的aio

https://grpc.github.io/grpc/python/grpc_asyncio.html

2. 直接使用proto文件

https://github.com/grpc/grpc/tree/master/examples/python/no_codegen

3. grpclib

https://github.com/vmagamedov/grpclib

3.1 proto

  1. syntax = "proto3";
  2. option go_package = ".;proto";
  3. service Greeter{
  4. rpc SayHello(HelloRequest) returns (HelloReply);
  5. }
  6. message HelloRequest{
  7. string name = 1;
  8. }
  9. message HelloReply{
  10. string message = 1;
  11. }

3.2 生成python源码

  1. pip install grpclib -i https://pypi.douban.com/simple #通过豆瓣镜像安装
  2. python -m grpc_tools.protoc --python_out=. --grpclib_python_out=. -I. helloworld.proto

3.3 服务端

  1. import asyncio
  2. from grpclib.utils import graceful_exit
  3. from grpclib.server import Server
  4. # generated by protoc
  5. from .helloworld_pb2 import HelloReply
  6. from .helloworld_grpc import GreeterBase
  7. class Greeter(GreeterBase):
  8. async def SayHello(self,stream):
  9. request = await stream.recv_message()
  10. message = f'Hello,{request.name}!'
  11. await stream.send_message(HelloReply(message=message))
  12. async def main(*, host='127.0.0.1', port=50051):
  13. server = Server([Greeter()])
  14. # Note: graceful_exit isn't supported in Windows
  15. await server.start(host,port)
  16. print(f'Serving on {host}:{port}')
  17. await server.wait_closed()
  18. if __name__ == "__main__":
  19. asyncio.run(main())

3.4 客户端

  1. import asyncio
  2. from grpclib.client import Channel
  3. # generated by protoc
  4. from .helloworld_pb2 import HelloRequest, HelloReply
  5. from .helloworld_grpc import GreeterStub
  6. async def main():
  7. async with Channel('127.0.0.1', 50051) as channel:
  8. greeter = GreeterStub(channel)
  9. reply = await greeter.SayHello(HelloRequest(name="Dr.Strange"))
  10. print(reply.message)
  11. if __name__ == '__main__':
  12. asyncio.run(main())