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
syntax = "proto3";
option go_package = ".;proto";
service Greeter{
rpc SayHello(HelloRequest) returns (HelloReply);
}
message HelloRequest{
string name = 1;
}
message HelloReply{
string message = 1;
}
3.2 生成python源码
pip install grpclib -i https://pypi.douban.com/simple #通过豆瓣镜像安装
python -m grpc_tools.protoc --python_out=. --grpclib_python_out=. -I. helloworld.proto
3.3 服务端
import asyncio
from grpclib.utils import graceful_exit
from grpclib.server import Server
# generated by protoc
from .helloworld_pb2 import HelloReply
from .helloworld_grpc import GreeterBase
class Greeter(GreeterBase):
async def SayHello(self,stream):
request = await stream.recv_message()
message = f'Hello,{request.name}!'
await stream.send_message(HelloReply(message=message))
async def main(*, host='127.0.0.1', port=50051):
server = Server([Greeter()])
# Note: graceful_exit isn't supported in Windows
await server.start(host,port)
print(f'Serving on {host}:{port}')
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())
3.4 客户端
import asyncio
from grpclib.client import Channel
# generated by protoc
from .helloworld_pb2 import HelloRequest, HelloReply
from .helloworld_grpc import GreeterStub
async def main():
async with Channel('127.0.0.1', 50051) as channel:
greeter = GreeterStub(channel)
reply = await greeter.SayHello(HelloRequest(name="Dr.Strange"))
print(reply.message)
if __name__ == '__main__':
asyncio.run(main())