|
| 1 | +import os |
| 2 | +from random import randint |
| 3 | + |
| 4 | +import boto3 |
| 5 | + |
| 6 | +from aws_lambda_powertools.utilities.batch import BasePartialProcessor, batch_processor |
| 7 | + |
| 8 | +table_name = os.getenv("TABLE_NAME", "table_not_found") |
| 9 | + |
| 10 | + |
| 11 | +class MyPartialProcessor(BasePartialProcessor): |
| 12 | + """ |
| 13 | + Process a record and stores successful results at a Amazon DynamoDB Table |
| 14 | +
|
| 15 | + Parameters |
| 16 | + ---------- |
| 17 | + table_name: str |
| 18 | + DynamoDB table name to write results to |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, table_name: str): |
| 22 | + self.table_name = table_name |
| 23 | + |
| 24 | + super().__init__() |
| 25 | + |
| 26 | + def _prepare(self): |
| 27 | + # It's called once, *before* processing |
| 28 | + # Creates table resource and clean previous results |
| 29 | + self.ddb_table = boto3.resource("dynamodb").Table(self.table_name) |
| 30 | + self.success_messages.clear() |
| 31 | + |
| 32 | + def _clean(self): |
| 33 | + # It's called once, *after* closing processing all records (closing the context manager) |
| 34 | + # Here we're sending, at once, all successful messages to a ddb table |
| 35 | + with self.ddb_table.batch_writer() as batch: |
| 36 | + for result in self.success_messages: |
| 37 | + batch.put_item(Item=result) |
| 38 | + |
| 39 | + def _process_record(self, record): |
| 40 | + # It handles how your record is processed |
| 41 | + # Here we're keeping the status of each run |
| 42 | + # where self.handler is the record_handler function passed as an argument |
| 43 | + try: |
| 44 | + result = self.handler(record) # record_handler passed to decorator/context manager |
| 45 | + return self.success_handler(record, result) |
| 46 | + except Exception as exc: |
| 47 | + return self.failure_handler(record, exc) |
| 48 | + |
| 49 | + def success_handler(self, record, result): |
| 50 | + entry = ("success", result, record) |
| 51 | + message = {"age": result} |
| 52 | + self.success_messages.append(message) |
| 53 | + return entry |
| 54 | + |
| 55 | + |
| 56 | +def record_handler(record): |
| 57 | + return randint(0, 100) |
| 58 | + |
| 59 | + |
| 60 | +@batch_processor(record_handler=record_handler, processor=MyPartialProcessor(table_name)) |
| 61 | +def lambda_handler(event, context): |
| 62 | + return {"statusCode": 200} |
0 commit comments