Getting started with the Dapr client Python SDK

How to get up and running with the Dapr Python SDK

The Dapr client package allows you to interact with other Dapr applications from a Python application.

Pre-requisites

Import the client package

The dapr package contains the DaprClient which will be used to create and use a client.

  1. from dapr.clients import DaprClient

Building blocks

The Python SDK allows you to interface with all of the Dapr building blocks.

Invoke a service

  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. # invoke a method (gRPC or HTTP GET)
  4. resp = d.invoke_method('service-to-invoke', 'method-to-invoke', data='{"message":"Hello World"}')
  5. # for other HTTP verbs the verb must be specified
  6. # invoke a 'POST' method (HTTP only)
  7. resp = d.invoke_method('service-to-invoke', 'method-to-invoke', data='{"id":"100", "FirstName":"Value", "LastName":"Value"}', http_verb='post')

Save & get application state

  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. # Save state
  4. d.save_state(store_name="statestore", key="key1", value="value1")
  5. # Get state
  6. data = d.get_state(store_name="statestore", key="key1").data
  7. # Delete state
  8. d.delete_state(store_name="statestore", key="key1")

Publish & subscribe to messages

Publish messages
  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. resp = d.publish_event(pubsub_name='pubsub', topic='TOPIC_A', data='{"message":"Hello World"}')
Subscribe to messages
  1. from cloudevents.sdk.event import v1
  2. from dapr.ext.grpc import App
  3. import json
  4. app = App()
  5. @app.subscribe(pubsub_name='pubsub', topic='TOPIC_A')
  6. def mytopic(event: v1.Event) -> None:
  7. data = json.loads(event.Data())
  8. print(f'Received: id={data["id"]}, message="{data ["message"]}"'
  9. ' content_type="{event.content_type}"',flush=True)

Interact with output bindings

  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. resp = d.invoke_binding(name='kafkaBinding', operation='create', data='{"message":"Hello World"}')

Retrieve secrets

  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. resp = d.get_secret(store_name='localsecretstore', key='secretKey')