Интеграция Lambda и DynamoDB
Разрабатывайте функции Lambda, взаимодействующие с DynamoDB для выполнения операций создания, чтения, обновления и удаления, создавая бессерверную серверную часть на основе данных
«Интеграция Lambda и DynamoDB» — бесплатный урок Serverless Backend with AWS Lambda & API Gateway на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Serverless Backend with AWS Lambda & API Gateway, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Lambda & DynamoDB: The Power Duo
Welcome to integrating AWS Lambda with DynamoDB! This combination is a cornerstone for building powerful, serverless backends.
AWS Lambda provides the compute power to run your code without managing servers, while DynamoDB offers a fast, flexible NoSQL database that scales automatically.
Together, they allow you to create data-driven applications that handle create, read, update, and delete (CRUD) operations efficiently.
Granting Lambda DynamoDB Access
Before your Lambda function can interact with DynamoDB, it needs permission. This is managed through an IAM Role attached to your Lambda function.
The IAM role must have a policy that grants specific DynamoDB actions, such as:
dynamodb:PutItem(for creating/updating)dynamodb:GetItem(for reading)dynamodb:UpdateItem(for modifying parts of an item)dynamodb:DeleteItem(for removing items)
Always follow the principle of least privilege: grant only the permissions necessary.
Connecting from Lambda with Boto3
In a Python Lambda function, you'll use the AWS SDK for Python, Boto3, to interact with DynamoDB. First, you need to initialize a DynamoDB client or resource.
The boto3.resource('dynamodb') approach is often preferred as it provides a higher-level, object-oriented interface.
Try running this example to see how to initialize the client:
import boto3
import json
def lambda_handler(event, context):
# Initialize DynamoDB resource
dynamodb = boto3.resource('dynamodb')
table_name = 'my-coddykit-table' # Placeholder
table = dynamodb.Table(table_name)
print(f"Connected to table: {table_name}")
return {
'statusCode': 200,
'body': json.dumps('DynamoDB client initialized!')
}
# For local testing/runnable snippet
if __name__ == '__main__':
print("Running handler locally...")
lambda_handler({}, {})Creating & Replacing Items (PutItem)
The put_item() method is used to create a new item or completely replace an existing item in a DynamoDB table.
- If an item with the same primary key already exists,
put_item()will overwrite it entirely. - If no item with that primary key exists, it will create a new one.
This operation is useful when you want to ensure an item exists with specific attributes, or you need to replace all its attributes.
PutItem in Action
Here's a Lambda function demonstrating how to use put_item() to add or update an item. We'll use a placeholder table name and item details from the event.
Run the code to see the simulated item creation!
import boto3
import json
def lambda_handler(event, context):
dynamodb = boto3.resource('dynamodb')
# Use a placeholder table name
table = dynamodb.Table('my-coddykit-table')
item_id = event.get('itemId', 'P001')
item_name = event.get('itemName', 'New Product')
table.put_item(
Item={
'itemId': item_id,
'itemName': item_name,
'category': 'Electronics'
}
)
print(f"Added/updated item: {item_id}")
return {
'statusCode': 200,
'body': json.dumps(f'Item {item_id} processed!')
}
# For local testing/runnable snippet
if __name__ == '__main__':
mock_event = {'itemId': 'P002', 'itemName': 'Coddy Phone'}
lambda_handler(mock_event, {})Reading Items (GetItem)
To retrieve a single item from a DynamoDB table, you use the get_item() method. This operation requires you to provide the full primary key of the item.
If your table has a simple primary key (only a Partition Key), you'll provide just that value. If it has a composite primary key (Partition Key and Sort Key), you must provide both.
get_item() is highly efficient for direct lookups.
GetItem in Action
This Lambda function shows how to retrieve an item using its itemId (assuming it's our primary key). The response will contain the item's attributes if found.
Run this example to see how get_item() works.
import boto3
import json
def lambda_handler(event, context):
dynamodb = boto3.resource('dynamodb')
# Use a placeholder table name
table = dynamodb.Table('my-coddykit-table')
item_id = event.get('itemId', 'P001') # Assume 'itemId' is the primary key
response = table.get_item(
Key={'itemId': item_id}
)
item = response.get('Item')
if item:
print(f"Found item: {item}")
return {
'statusCode': 200,
'body': json.dumps(item)
}
else:
print(f"Item {item_id} not found.")
return {
'statusCode': 404,
'body': json.dumps(f'Item {item_id} not found.')
}
# For local testing/runnable snippet
if __name__ == '__main__':
mock_event = {'itemId': 'P002'} # Try to get an item
lambda_handler(mock_event, {})Modifying Parts of an Item (UpdateItem)
The update_item() method allows you to modify specific attributes of an existing item without replacing the entire item.
This is more efficient than put_item() if you only need to change a few attributes. It requires an UpdateExpression to specify which attributes to modify and how.
Update expressions can add, set, remove, or delete attributes.
Removing Items (DeleteItem)
To delete an item from a DynamoDB table, you use the delete_item() method. Similar to get_item(), you must provide the full primary key of the item you wish to remove.
Once an item is deleted, it cannot be recovered through this operation. Be cautious when using delete_item(), especially in production environments.
Quick Check: DynamoDB Operations
You need to create a new user profile in your DynamoDB Users table. If a user with the same ID already exists, you want to completely overwrite their old profile with the new data. Which Boto3 method should your Lambda function use?
Recap: Lambda & DynamoDB Integration
Great job! You've learned how to integrate AWS Lambda with DynamoDB to build data-driven serverless applications.
- We covered the importance of IAM permissions for secure access.
- You saw how to use the Boto3 SDK to connect from Python Lambda.
- We explored the core CRUD operations:
put_item()(create/replace),get_item()(read),update_item()(modify), anddelete_item()(remove).
This knowledge is crucial for developing robust serverless backends!
Часто задаваемые вопросы
Урок «Интеграция Lambda и DynamoDB» бесплатный?
Да — полный текст урока «Интеграция Lambda и DynamoDB» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Serverless Backend with AWS Lambda & API Gateway, подпишись на CoddyKit PRO. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.
Чему я научусь в уроке «Интеграция Lambda и DynamoDB»?
Разрабатывайте функции Lambda, взаимодействующие с DynamoDB для выполнения операций создания, чтения, обновления и удаления, создавая бессерверную серверную часть на основе данных Ты практикуешь Serverless Backend with AWS Lambda & API Gateway с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Serverless Backend with AWS Lambda & API Gateway?
Предыдущий опыт не требуется. Serverless Backend with AWS Lambda & API Gateway на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Интеграция Lambda и DynamoDB»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Serverless Backend with AWS Lambda & API Gateway?
Да. Каждый урок Serverless Backend with AWS Lambda & API Gateway включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в DynamoDB
- Проектирование таблиц DynamoDB
- Интеграция Lambda и DynamoDB
- Запросы по вторичным индексам: GSI и LSI