Muffin框架的GRPC支持。
项目描述
松饼-GRPC – 为Muffin框架提供GRPC支持。
功能
自动构建proto文件及其Python辅助工具;
自动连接到默认通道;
自动从您的服务创建和运行GRPC服务器;
要求
python >= 3.8
安装
松饼-GRPC应使用pip安装
pip install muffin-grpc
使用
设置插件并将其连接到您的应用程序
from muffin import Application
from muffin_grpc import Plugin as GRPC
# Create Muffin Application
app = Application('example')
# Initialize the plugin
# As alternative: grpc = GRPC(app, **options)
grpc = GRPC(default_channel='server:50051')
grpc.setup(app)
让我们构建一个简单的helloworld服务,使用proto
syntax = "proto3"; package helloworld; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
将其放在某个位置并将文件添加到grpc插件中
grpc.add_proto('project_name/proto/helloworld.proto')
运行命令以构建proto文件
$ muffin project_name grpc_build
命令将构建文件
project_name/proto/helloworld_pb2.py - 包含proto的消息
project_name/proto/helloworld_pb2_grpc.py - 包含proto的GRPC服务
project_name/proto/helloworld.py - 包含消息和服务
project_name/proto/__init__.py - 使构建目录成为包
让我们实现Greeter服务
from .proto.helloworld import GreeterServicer, HelloRequest, HelloReply
# Connect the service to GRPC server
@grpc.add_to_server
class Greeter(GreeterServicer):
async def SayHello(self, request: HelloRequest,
context: grpc_aio.ServicerContext) -> HelloReply:
return HelloReply(message='Hello, %s!' % request.name)
使用命令运行服务器
$ muffin package_name grpc_server
服务器正在运行并接受GRPC请求,让我们开始构建客户端
from .proto.helloworld import GreeterStub, HelloRequest
@app.route('/')
async def index(request):
name = request.url.query.get('name') or 'anonymous'
try:
async with grpc.get_channel() as channel:
stub = GreeterStub(channel)
response = await stub.SayHello(
HelloRequest(name=request.url.query['name']), timeout=10)
message = response.message
except AioRpcError as exc:
message = exc.details()
return message
/端点将向GRPC服务器发送请求并返回服务器消息。
配置选项
名称 |
默认值 |
描述 |
build_dir |
None |
构建proto文件的目录 |
server_listen |
"[::]:50051" |
服务器地址 |
ssl_server |
False |
启用服务器SSL |
ssl_server_params |
None |
SSL服务器参数 |
ssl_client |
False |
启用客户端SSL |
ssl_client_params |
None |
SSL客户端参数 |
default_channel |
localhost:50051 |
默认客户端通道地址 |
default_channel_options |
{} |
默认通道的GRPC选项 |
您可以在初始化插件时提供这些选项
grpc.setup(app, server_listen='localhost:40000')
或者从使用GRPC_前缀的Muffin.Application配置中设置它
GRPC_SERVER_LISTERN = 'locahost:40000'
Muffin.Application配置选项不区分大小写
CLI命令
$ muffin project_name grpc_build --help usage: muffin grpc_build [-h] Build registered proto files. optional arguments: -h, --help show this help message and exit
$ muffin project_name grpc_server --help usage: muffin grpc_server [-h] Start GRPC server with the registered endpoints. optional arguments: -h, --help show this help message and exit
错误跟踪器
如果您有任何建议、错误报告或不满,请向https://github.com/klen/muffin-grpc/issues的问题跟踪器报告
贡献
Muffin-GRPC的开发发生在:https://github.com/klen/muffin-grpc
贡献者
klen (Kirill Klenov)
许可证
署名于MIT许可。
项目详情
下载文件
为您的平台下载文件。如果您不确定选择哪个,请了解更多关于安装包的信息。