Dapr 클라이언트 Python SDK 시작하기
Dapr Python SDK를 시작하고 실행하는 방법을 알아봐요. Dapr 클라이언트 패키지를 사용하면 Python 애플리케이션에서 다른 Dapr 애플리케이션과 상호작용할 수 있어요.
참고 (Note)
아직 안 했다면, Dapr Python SDK를 API 빌딩 블록과 함께 사용하는 방법을 빠르게 익힐 수 있도록 퀵스타트 중 하나를 시도해 보세요.
출처: Dapr 문서
본문
사전 준비사항 (Prerequisites)
시작하기 전에 Dapr Python 패키지를 설치해요.
클라이언트 패키지 가져오기
dapr 패키지에는 클라이언트를 만들고 사용하는 데 쓰이는 DaprClient가 포함되어 있어요.
from dapr.clients import DaprClient
클라이언트 초기화하기
Dapr 클라이언트는 여러 가지 방법으로 초기화할 수 있어요:
기본값 (Default values):
매개변수 없이 클라이언트를 초기화하면 Dapr 사이드카 인스턴스의 기본값(127.0.0.1:50001)을 사용해요.
from dapr.clients import DaprClient
with DaprClient() as d:
초기화 시 엔드포인트 지정:
생성자에서 인자로 전달하면 gRPC 엔드포인트가 어떤 구성이나 환경 변수보다 우선해요.
from dapr.clients import DaprClient
with DaprClient("mydomain:50051?tls=true") as d:
구성 옵션 (Configuration options):
Dapr 사이드카 엔드포인트
표준화된 DAPR_GRPC_ENDPOINT 환경 변수를 사용해서 gRPC 엔드포인트를 지정할 수 있어요. 이 변수가 설정되면 클라이언트를 인자 없이 초기화할 수 있어요:
export DAPR_GRPC_ENDPOINT="mydomain:50051?tls=true"
from dapr.clients import DaprClient
with DaprClient() as d:
레거시 환경 변수 DAPR_RUNTIME_HOST, DAPR_HTTP_PORT, DAPR_GRPC_PORT도 지원되지만, DAPR_GRPC_ENDPOINT가 우선해요.
Dapr API 토큰
Dapr 인스턴스가 DAPR_API_TOKEN 환경 변수를 요구하도록 구성되어 있다면, 환경에 설정하면 클라이언트가 자동으로 사용해요.
Dapr API 토큰 인증에 대해 더 자세히 읽을 수 있어요 (여기).
헬스 타임아웃 (Health timeout)
클라이언트 초기화 시 Dapr 사이드카(/healthz/outbound)에 대한 헬스 체크가 수행돼요. 클라이언트는 진행하기 전에 사이드카가 실행될 때까지 기다려요.
기본 헬스체크 타임아웃은 60초이며, DAPR_HEALTH_TIMEOUT 환경 변수를 설정해서 재정의할 수 있어요.
재시도와 타임아웃 (Retries and timeout)
Dapr 클라이언트는 사이드카에서 특정 오류 코드를 받으면 요청을 재시도할 수 있어요. 이것은 DAPR_API_MAX_RETRIES 환경 변수로 구성할 수 있고 자동으로 감지되므로 코드 변경이 필요 없어요.
DAPR_API_MAX_RETRIES의 기본값은 0으로, 재시도가 없다는 뜻이에요.
dapr.clients.retry.RetryPolicy 객체를 만들어 DaprClient 생성자에 전달하면 더 세밀한 재시도 파라미터를 조정할 수 있어요:
from dapr.clients.retry import RetryPolicy
retry = RetryPolicy(
max_attempts=5,
initial_backoff=1,
max_backoff=20,
backoff_multiplier=1.5,
retryable_http_status_codes=[408, 429, 500, 502, 503, 504],
retryable_grpc_status_codes=[StatusCode.UNAVAILABLE, StatusCode.DEADLINE_EXCEEDED, ]
)
with DaprClient(retry_policy=retry) as d:
...
또는 액터의 경우:
factory = ActorProxyFactory(retry_policy=RetryPolicy(max_attempts=3))
proxy = ActorProxy.create('DemoActor', ActorId('1'), DemoActorInterface, factory)
모든 호출에 대한 타임아웃은 DAPR_API_TIMEOUT_SECONDS 환경 변수로 설정할 수 있어요. 기본값은 60초예요.
참고: 서비스 호출에서 타임아웃을 별도로 제어하려면 invoke_method 메서드에 timeout 파라미터를 전달하면 돼요.
오류 처리 (Error handling)
처음에는 Dapr의 오류가 표준 gRPC 오류 모델을 따랐어요. 하지만 1.13 버전에서는 더 상세하고 정보가 풍부한 오류 메시지를 제공하기 위해 gRPC Richer 오류 모델에 맞춘 향상된 오류 모델이 도입됐어요. 이에 대응하여 Python SDK는 개발자 경험을 개선하도록 설계된 커스텀 예외 클래스 DaprGrpcError를 구현했어요.
모든 gRPC 상태 예외에 DaprGrpcError를 사용하도록 전환하는 것은 진행 중인 작업이라는 점을 기억하는 것이 중요해요. 현재 SDK의 모든 API 호출이 이 커스텀 예외를 활용하도록 업데이트된 것은 아니에요. 우리는 이 개선 작업을 적극적으로 진행 중이며 커뮤니티의 기여를 환영해요.
Dapr python-SDK를 사용할 때 DaprGrpcError 예외를 처리하는 예시:
try:
d.save_state(store_name=storeName, key=key, value=value)
except DaprGrpcError as err:
print(f'Status code: {err.code()}')
print(f"Message: {err.message()}")
print(f"Error code: {err.error_code()}")
print(f"Error info(reason): {err.error_info.reason}")
print(f"Resource info (resource type): {err.resource_info.resource_type}")
print(f"Resource info (resource name): {err.resource_info.resource_name}")
print(f"Bad request (field): {err.bad_request.field_violations[0].field}")
print(f"Bad request (description): {err.bad_request.field_violations[0].description}")
빌딩 블록 (Building blocks)
Python SDK를 사용하면 모든 Dapr 빌딩 블록과 인터페이스할 수 있어요.
서비스 호출 (Invoke a service)
Dapr Python SDK는 HTTP 또는 gRPC(비권장)를 통해 서비스를 호출하는 간단한 API를 제공해요. DAPR_API_METHOD_INVOCATION_PROTOCOL 환경 변수를 설정해서 프로토콜을 선택할 수 있고, 설정하지 않으면 기본값은 HTTP예요. Dapr의 GRPC 서비스 호출은 비권장이며 대신 GRPC 프록시를 권장해요.
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.invoke_method('service-to-invoke', 'method-to-invoke', data='{"message":"Hello World"}')
resp = d.invoke_method('service-to-invoke', 'method-to-invoke', data='{"id":"100", "FirstName":"Value", "LastName":"Value"}', http_verb='post')
HTTP API 호출의 기본 엔드포인트는 DAPR_HTTP_ENDPOINT 환경 변수에 지정돼요.
이 변수가 설정되지 않으면 엔드포인트 값은 DAPR_RUNTIME_HOST와 DAPR_HTTP_PORT 변수에서 파생되는데, 기본값은 각각 127.0.0.1과 3500이에요.
gRPC 호출의 기본 엔드포인트는 클라이언트 초기화에 사용된 엔드포인트(위에서 설명)예요.
- 서비스 호출에 대한 전체 가이드는 How-To: 서비스 호출하기를 참고해 주세요.
- 서비스 호출을 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
애플리케이션 상태 저장 & 조회 (Save & get application state)
from dapr.clients import DaprClient
with DaprClient() as d:
d.save_state(store_name="statestore", key="key1", value="value1")
data = d.get_state(store_name="statestore", key="key1").data
d.delete_state(store_name="statestore", key="key1")
- 상태 연산의 전체 목록은 How-To: 상태 조회 & 저장을 참고해 주세요.
- 상태 관리를 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
애플리케이션 상태 조회 (Alpha)
from dapr import DaprClient
query = '''
{
"filter": {
"EQ": { "state": "CA" }
},
"sort": [
{
"key": "person.id",
"order": "DESC"
}
]
}
'''
with DaprClient() as d:
resp = d.query_state(
store_name='state_store',
query=query,
states_metadata={"metakey": "metavalue"}, # optional
)
- 상태 저장소 조회 옵션의 전체 목록은 How-To: 상태 조회하기를 참고해 주세요.
- 상태 저장소 조회를 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
게시 & 구독 (Publish & subscribe)
메시지 게시하기
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.publish_event(pubsub_name='pubsub', topic_name='TOPIC_A', data='{"message":"Hello World"}')
json 페이로드로 CloudEvents 메시지 보내기:
from dapr.clients import DaprClient
import json
with DaprClient() as d:
cloud_event = {
'specversion': '1.0',
'type': 'com.example.event',
'source': 'my-service',
'id': 'myid',
'data': {'id': 1, 'message': 'hello world'},
'datacontenttype': 'application/json',
}
resp = d.publish_event(
pubsub_name='pubsub',
topic_name='TOPIC_CE',
data=json.dumps(cloud_event),
data_content_type='application/cloudevents+json',
)
일반 텍스트 페이로드로 CloudEvents 메시지 보내기:
from dapr.clients import DaprClient
import json
with DaprClient() as d:
cloud_event = {
'specversion': '1.0',
'type': 'com.example.event',
'source': 'my-service',
'id': "myid",
'data': 'hello world',
'datacontenttype': 'text/plain',
}
resp = d.publish_event(
pubsub_name='pubsub',
topic_name='TOPIC_CE',
data=json.dumps(cloud_event),
data_content_type='application/cloudevents+json',
)
메시지 구독하기
from cloudevents.sdk.event import v1
from dapr.ext.grpc import App
import json
app = App()
@app.subscribe(pubsub_name='pubsub', topic='TOPIC_A')
def mytopic(event: v1.Event) -> None:
data = json.loads(event.Data())
print(f'Received: id={data["id"]}, message="{data ["message"]}"'
' content_type="{event.content_type}"',flush=True)
@app.subscribe(pubsub_name='pubsub', topic='TOPIC_A',
rule=Rule("event.type == \"important\"", 1))
def mytopic_important(event: v1.Event) -> None:
data = json.loads(event.Data())
print(f'Received: id={data["id"]}, message="{data ["message"]}"'
' content_type="{event.content_type}"',flush=True)
- pub/sub에 대한 더 자세한 내용은 How-To: 게시 & 구독을 참고해 주세요.
- pub/sub을 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
스트리밍 메시지 구독 (Streaming message subscription)
subscribe 또는 subscribe_handler 메서드를 사용해서 PubSub 토픽에 스트리밍 구독을 만들 수 있어요.
subscribe 메서드는 순회 가능한(iterable) Subscription 객체를 반환하는데, for 루프(예: for message in subscription)를 사용하거나 next_message 메서드를 호출해서 스트림에서 메시지를 가져올 수 있어요. 이렇게 하면 메시지를 기다리는 동안 메인 스레드가 차단돼요.
완료되면 close 메서드를 호출해서 구독을 종료하고 메시지 수신을 중지해야 해요.
subscribe_with_handler 메서드는 스트림에서 받은 각 메시지에 대해 실행되는 콜백 함수를 받아요.
이것은 별도의 스레드에서 실행되므로 메인 스레드를 차단하지 않아요. 콜백은 메시지가 성공적으로 처리되었는지, 재시도해야 하는지, 버려야 하는지 나타내는 TopicEventResponse(예: TopicEventResponse('success'))를 반환해야 해요. 이 메서드는 반환된 상태에 따라 메시지 승인(acknowledgement)을 자동으로 관리해요. subscribe_with_handler 메서드 호출은 close 함수를 반환하며, 완료되면 구독을 종료하기 위해 이 함수를 호출해야 해요.
subscribe 메서드 사용 예시:
import time
from dapr.clients import DaprClient
from dapr.clients.grpc.subscription import StreamInactiveError, StreamCancelledError
counter = 0
def process_message(message):
global counter
counter += 1
print(f'Processing message: {message.data()} from {message.topic()}...')
return 'success'
def main():
with DaprClient() as client:
global counter
subscription = client.subscribe(
pubsub_name='pubsub', topic='TOPIC_A', dead_letter_topic='TOPIC_A_DEAD'
)
try:
for message in subscription:
if message is None:
print('No message received. The stream might have been cancelled.')
continue
try:
response_status = process_message(message)
if response_status == 'success':
subscription.respond_success(message)
elif response_status == 'retry':
subscription.respond_retry(message)
elif response_status == 'drop':
subscription.respond_drop(message)
if counter >= 5:
break
except StreamInactiveError:
print('Stream is inactive. Retrying...')
time.sleep(1)
continue
except StreamCancelledError:
print('Stream was cancelled')
break
except Exception as e:
print(f'Error occurred during message processing: {e}')
finally:
print('Closing subscription...')
subscription.close()
if __name__ == '__main__':
main()
그리고 subscribe_with_handler 메서드 사용 예시:
import time
from dapr.clients import DaprClient
from dapr.clients.grpc._response import TopicEventResponse
counter = 0
def process_message(message):
global counter
counter += 1
print(f'Processing message: {message.data()} from {message.topic()}...')
return TopicEventResponse('success')
def main():
with (DaprClient() as client):
close_fn = client.subscribe_with_handler(
pubsub_name='pubsub', topic='TOPIC_A', handler_fn=process_message,
dead_letter_topic='TOPIC_A_DEAD'
)
while counter < 5:
time.sleep(1)
print("Closing subscription...")
close_fn()
if __name__ == '__main__':
main()
- pub/sub에 대한 더 자세한 내용은 How-To: 게시 & 구독을 참고해 주세요.
- 스트리밍 pub/sub을 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
대화 (Conversation) (Alpha)
참고 (Note)
Dapr Conversation API는 현재 alpha 단계예요. 1.15 버전부터 Dapr은 Conversation API를 통해 대규모 언어 모델(LLM)과 안전하고 안정적으로 상호작용할 수 있는 기능을 개발자에게 제공해요.
from dapr.clients import DaprClient
from dapr.clients.grpc.conversation import ConversationInput
with DaprClient() as d:
inputs = [
ConversationInput(content="What's Dapr?", role='user', scrub_pii=True),
ConversationInput(content='Give a brief overview.', role='user', scrub_pii=True),
]
metadata = {
'model': 'foo',
'key': 'authKey',
'cacheTTL': '10m',
}
response = d.converse_alpha1(
name='echo', inputs=inputs, temperature=0.7, context_id='chat-123', metadata=metadata
)
for output in response.outputs:
print(f'Result: {output.result}')
출력 바인딩과 상호작용하기
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.invoke_binding(binding_name='kafkaBinding', operation='create', data='{"message":"Hello World"}')
- 출력 바인딩에 대한 전체 가이드는 How-To: 바인딩 사용하기를 참고해 주세요.
- 출력 바인딩을 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
비밀 조회하기
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.get_secret(store_name='localsecretstore', key='secretKey')
- 비밀에 대한 전체 가이드는 How-To: 비밀 조회하기를 참고해 주세요.
- 비밀 조회를 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
구성 (Configuration)
구성 가져오기
from dapr.clients import DaprClient
with DaprClient() as d:
configuration = d.get_configuration(store_name='configurationstore', keys=['orderId'], config_metadata={})
구성 구독하기
import asyncio
from time import sleep
from dapr.clients import DaprClient
async def executeConfiguration():
with DaprClient() as d:
storeName = 'configurationstore'
key = 'orderId'
d.wait(20)
configuration = await d.subscribe_configuration(store_name=storeName, keys=[key], config_metadata={})
while True:
if configuration != None:
items = configuration.get_items()
for key, item in items:
print(f"Subscribe key={key} value={item.value} version={item.version}", flush=True)
else:
print("Nothing yet")
sleep(5)
asyncio.run(executeConfiguration())
- 구성 관리에 대해 더 알아보려면 How-To: 구성 관리하기 가이드를 참고해 주세요.
- 구성을 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
분산 락 (Distributed Lock)
from dapr.clients import DaprClient
def main():
store_name = 'lockstore' # as defined in components/lockstore.yaml
resource_id = 'example-lock-resource'
client_id = 'example-client-id'
expiry_in_seconds = 60
with DaprClient() as dapr:
print('Will try to acquire a lock from lock store named [%s]' % store_name)
print('The lock is for a resource named [%s]' % resource_id)
print('The client identifier is [%s]' % client_id)
print('The lock will will expire in %s seconds.' % expiry_in_seconds)
with dapr.try_lock(store_name, resource_id, client_id, expiry_in_seconds) as lock_result:
assert lock_result.success, 'Failed to acquire the lock. Aborting.'
print('Lock acquired successfully!!!')
unlock_result = dapr.unlock(store_name, resource_id, client_id)
print('We already released the lock so unlocking will not work.')
print('We tried to unlock it anyway and got back [%s]' % unlock_result.status)
- 분산 락 사용에 대해 더 알아보기: How-To: 락 사용하기.
- 분산 락을 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
암호화 (Cryptography)
from dapr.clients import DaprClient
message = 'The secret is "passw0rd"'
def main():
with DaprClient() as d:
resp = d.encrypt(
data=message.encode(),
options=EncryptOptions(
component_name='crypto-localstorage',
key_name='rsa-private-key.pem',
key_wrap_algorithm='RSA',
),
)
encrypt_bytes = resp.read()
resp = d.decrypt(
data=encrypt_bytes,
options=DecryptOptions(
component_name='crypto-localstorage',
key_name='rsa-private-key.pem',
),
)
decrypt_bytes = resp.read()
print(decrypt_bytes.decode()) # The secret is "passw0rd"
- 상태 연산의 전체 목록은 How-To: 암호화 API 사용하기를 참고해 주세요.
- 암호화를 시도하기 위한 코드 샘플과 지침은 Python SDK 예제를 방문해 주세요.
관련 링크 (Related links)
Python SDK 예제