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")

Query application state (Alpha)

  1. from dapr import DaprClient
  2. query = '''
  3. {
  4. "filter": {
  5. "EQ": { "state": "CA" }
  6. },
  7. "sort": [
  8. {
  9. "key": "person.id",
  10. "order": "DESC"
  11. }
  12. ]
  13. }
  14. '''
  15. with DaprClient() as d:
  16. resp = d.query_state(
  17. store_name='state_store',
  18. query=query,
  19. states_metadata={"metakey": "metavalue"}, # optional
  20. )

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_name='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. # Default subscription for a topic
  6. @app.subscribe(pubsub_name='pubsub', topic='TOPIC_A')
  7. def mytopic(event: v1.Event) -> None:
  8. data = json.loads(event.Data())
  9. print(f'Received: id={data["id"]}, message="{data ["message"]}"'
  10. ' content_type="{event.content_type}"',flush=True)
  11. # Specific handler using Pub/Sub routing
  12. @app.subscribe(pubsub_name='pubsub', topic='TOPIC_A',
  13. rule=Rule("event.type == \"important\"", 1))
  14. def mytopic_important(event: v1.Event) -> None:
  15. data = json.loads(event.Data())
  16. print(f'Received: id={data["id"]}, message="{data ["message"]}"'
  17. ' 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(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')

Get configuration

  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. # Get Configuration
  4. configuration = d.get_configuration(store_name='configurationstore', keys=['orderId'], config_metadata={})

Subscribe to configuration

  1. import asyncio
  2. from time import sleep
  3. from dapr.clients import DaprClient
  4. async def executeConfiguration():
  5. with DaprClient() as d:
  6. storeName = 'configurationstore'
  7. key = 'orderId'
  8. # Wait for sidecar to be up within 20 seconds.
  9. d.wait(20)
  10. # Subscribe to configuration by key.
  11. configuration = await d.subscribe_configuration(store_name=storeName, keys=[key], config_metadata={})
  12. while True:
  13. if configuration != None:
  14. items = configuration.get_items()
  15. for key, item in items:
  16. print(f"Subscribe key={key} value={item.value} version={item.version}", flush=True)
  17. else:
  18. print("Nothing yet")
  19. sleep(5)
  20. asyncio.run(executeConfiguration())