Skip to content

Latest commit

 

History

History
184 lines (120 loc) · 11.2 KB

README.md

File metadata and controls

184 lines (120 loc) · 11.2 KB

Explore the Distributed Application Runtime (Dapr) with Python

Dapr is a portable, serverless, event-driven runtime that makes it easy for developers to build resilient, stateless and stateful microservices that run on the cloud and edge and embraces the diversity of languages and developer frameworks.

You can learn more about Dapr at dapr.io, github.com/dapr/dapr, @dapr (twitter.com), the Dapr Discord, Introducing Dapr (2:27) (youtube.com) and aka.ms/hello-dapr.

Dapr was announced in October 2019 and reached v1.0 in February 2021, is now v1.1.0, and has over 13.1k GitHub stars as of May 2021. It is used in production by customers including ZEISS, Ignition Group, Roadwork, Alibaba Cloud and many more.

Dapr uses a sidecar architecture, as a simple process, or in a container (with or without Kubernetes), to provide microservice building blocks for cloud and edge that include:

Dapr uses Components for State stores, Service discovery, Middleware, Pub/sub brokers, Bindings, and Secret stores. These include both self-hosted, open source, and managed platforms across multiple clouds. They enable your application to be portable across local development, on-premesis and cloud environments.

Dapr can be used via HTTP, gRPC, and language-specific SDKs for languages inlcuding .NET, Python, Java, Go, PHP, C++, Rust and JavaScript

What you will learn

You will:

  • Get hands-on with Dapr by running it on your local machine through the Try Dapr experience.
  • Explore State Mangement and Secrets building blocks via the REST API using cURL (optional), Python Requests, and the Dapr SDK for Python (dapr/python-sdk).
  • Seamlessly swap the State component from local development to a managed service in the cloud.

Prerequisites

Try Dapr

In order to use Dapr locally you will need to install the Dapr CLI and local components using

Install the Dapr CLI on macOS, Windows or Linux via the above link.

Initialize Dapr using the dapr init command. This step assumes we are using Docker.

We will now run the dapr sidecar using the dapr CLI:

dapr run --app-id myapp --dapr-http-port 3500

Congratulations, you will now have REST API for the automatically configured State management building block available via HTTP on http://localhost:3500/v1.0/state/statestore

You can do a quick test by running the following to save and get some state:

# save state
curl -X POST -H "Content-Type: application/json" -d '[{ "key": "name", "value": "Bruce Wayne"}]' 'http://localhost:3500/v1.0/state/statestore'
# get state
curl http://localhost:3500/v1.0/state/statestore/name

Instead of using bash (curl) or PowerShell (Invoke-RestMethod), we can continue to explore it with Python using both Python Requests against the REST API, and the Dapr SDK for Python (dapr/python-sdk).

3.1. Install requirements for CLI

Install Python Fire, Python Requests and the Dapr SDK for Python

# clone this repository locally
git clone https://github.com/Azure-Samples/azure-python-labs.git

# cd into the correct directory
cd azure-python-labs/01-dapr

# create and activate a virtual environment
python3 -m venv env
source env/bin/activate

# install dependencies
pip install -r requirements.txt

3.2 Get and set state via Python Requests and the Dapr SDK for Python

Let's start (or restart) our dapr sidecar in its own terminal window, but this time in addition to the HTTP port for curl and Python Requests, we will also need to provide a gRPC port for the Python SDK which uses gRPC by default and defaults to port 50001:

dapr run --app-id myapp --dapr-http-port 3500 --dapr-grpc-port 50001

Now if we run python main.py in another terminal window we can see the list of commands (see: help.txt).

Explore main.py and the # http examples and # sdk examples:

# http examples
def dapr_http_get_state(store="statestore", name="name"):
    """GET /v1.0/state/{store}/{name}"""
    port = os.getenv("DAPR_HTTP_PORT") or "3500"
    r = requests.get(f"http://localhost:{port}/v1.0/state/{store}/{name}")
    print(r.json())

# ...

# sdk examples
def dapr_get_state(store="statestore", name="name"):
    """DaprClient().get_state(store_name=store, key=name)"""
    with dapr.clients.DaprClient() as d:
        # Wait for sidecar to be up within 5 seconds.
        d.wait(5)
        res = d.get_state(store_name=store, key=name)
        print(res.data.decode())

You can execute these as follows:

# get state with requests over http
python main.py dapr_http_get_state
# get state with sdk over grpc
python main.py dapr_get_state

We can override parameters as follows, and use the --help flag to view help text (example: help_dapr_http_get_state.txt) including the parameters you can use.

# get help text
python main.py dapr_save_state --help

python main.py dapr_http_post_state --store="statestore" --name="me" --value="hello" 

python main.py dapr_http_get_state --name "me"

python main.py dapr_save_state --store="statestore" --name="me" --value="world" 

python main.py dapr_get_state --store="statestore" --name="me"

3.3 Explore the Secret building block

Another building block we will explore is Secrets.

We are going to use the Local file secret store which we have pre-configured in my-components/localSecretStore.yaml with secrets stored in my-secrets.json.

In order to reference the components configured in my-components, we will need to pass the --components-path flag when we run the dapr sidecar.

In your first terminal, run:

cd azure-python-labs/01-dapr

dapr run --app-id myapp --dapr-http-port 3500 --dapr-grpc-port 50001 --components-path ./my-components

In your second terminal, run:

python main.py dapr_http_get_secret --name "my-secret"
python main.py dapr_get_secret --name "my-secret"

Are you ready to explore further? These SDK snippets were taken directly from the Dapr SDK for Python examples and you can copy/paste into your own functions in main.py. We'd also love to hear your feedback on the SDK, the examples, and how you use Dapr with Python!

Now you have used Dapr with Python via the HTTP API and the Dapr SDK for Python, you may wish to continue the Try Dapr experience to "Configure a component" and "Explore Dapr quickstarts".

Optional Challenge: Send your state to the cloud with Azure Blob Storage

Can you take your state store to the Cloud with Azure Blob Storage? Your above code will require zero changes! Here are some hints: