Getting started with the Dapr Python gRPC service extension

How to get up and running with the Dapr Python gRPC extension package

The Dapr Python SDK provides a built in gRPC server extension module, dapr.ext.grpc, for creating Dapr services.

安装

You can download and install the Dapr gRPC server extension module with:

  1. pip install dapr-ext-grpc

Note

开发包包含的功能和行为将兼容此前发行的 Dapr 运行时。 在安装 dapr-dev 包之前,请务必卸载以前任意稳定版本的 dapr-ext-fastapi 的 Python SDK 扩展包。

  1. pip3 install dapr-ext-grpc-dev

示例

The App object can be used to create a server.

Listen for service invocation requests

The InvokeServiceReqest and InvokeServiceResponse objects can be used to handle incoming requests.

A simple service that will listen and respond to requests will look like:

  1. from dapr.ext.grpc import App, InvokeServiceRequest, InvokeServiceResponse
  2. app = App()
  3. @app.method(name='my-method')
  4. def mymethod(request: InvokeServiceRequest) -> InvokeServiceResponse:
  5. print(request.metadata, flush=True)
  6. print(request.text(), flush=True)
  7. return InvokeServiceResponse(b'INVOKE_RECEIVED', "text/plain; charset=UTF-8")
  8. app.run(50051)

A full sample can be found here.

Subscribe to a topic

  1. from cloudevents.sdk.event import v1
  2. from dapr.ext.grpc import App
  3. app = App()
  4. @app.subscribe(pubsub_name='pubsub', topic='TOPIC_A')
  5. def mytopic(event: v1.Event) -> None:
  6. print(event.Data(),flush=True)
  7. app.run(50051)

A full sample can be found here.

Setup input binding trigger

  1. from dapr.ext.grpc import App, BindingRequest
  2. app = App()
  3. @app.binding('kafkaBinding')
  4. def binding(request: BindingRequest):
  5. print(request.text(), flush=True)
  6. app.run(50051)

A full sample can be found here.

相关链接