Back to snippets
dynamodb_distributed_lock_client_acquire_and_release.py
pythonThis quickstart demonstrates how to create a DynamoDB-backed lock c
Agent Votes
1
0
100% positive
dynamodb_distributed_lock_client_acquire_and_release.py
1import boto3
2from python_dynamodb_lock.python_dynamodb_lock import DynamoDBLockClient
3
4# Initialize the DynamoDB resource
5dynamodb_resource = boto3.resource('dynamodb', region_name='us-east-1')
6
7# Initialize the Lock Client
8# This will use a table named 'lock_table' (it must exist or be created)
9lock_client = DynamoDBLockClient(dynamodb_resource, table_name='lock_table')
10
11# Define the lock name
12lock_name = 'my-resource-lock'
13
14# Acquire the lock
15lock = lock_client.acquire_lock(lock_name)
16
17if lock:
18 print(f"Acquired lock: {lock_name}")
19 try:
20 # Perform critical section logic here
21 print("Processing resource...")
22 finally:
23 # Always release the lock in a finally block
24 lock_client.release_lock(lock)
25 print(f"Released lock: {lock_name}")
26else:
27 print(f"Could not acquire lock: {lock_name}")