Chapter 93: AWS Lambda and Serverless for DevOps
93.2 Handlers, events and context
Story (fictional teaching scenario). Rohan from Nashik asks fictional teammate Maya from Toronto where Lambda starts running Python. She points at one named function, not the first line of the file.
Why
A clear entry point lets you test the same business code locally and use it later with a cloud event.
What
- Handler is the entry-point function Lambda calls.
- event is its first argument: the request data.
- context is its second argument: AWS runtime information such as request ID and remaining time.
- Return value is the result returned to the invoker. Different integrations expect different shapes.
How
-
Put the handler in price.py.
-
Use the same two argument names in local tests.
-
Do not assume a fake local context has real AWS metadata.
Example 1: Read a tiny handler
- Read the input and the code.
def lambda_handler(event, context):
total = event['qty'] * event['unit_paise']
return {'total_paise': total, 'currency': 'INR'}
- Read the result.
Output (illustrative; not executed on AWS)
{'total_paise': 12000, 'currency': 'INR'}
- What each part means:
defdeclares the entry function. The next line reads input fields and multiplies them.returnmakes a dictionary that the runtime can serialize. Handler settingprice.lambda_handlermeans fileprice.py, functionlambda_handler. Input validation is added in the local lab.
Example 2: Context is not the event
- Read the input and the code.
def describe_context(context):
return {'request_id': context.aws_request_id,
'remaining_ms': context.get_remaining_time_in_millis()}
- Read the result.
Output (illustrative; not executed on AWS)
{'request_id': 'demo-request-1', 'remaining_ms': 2800}
- What each part means:
aws_request_idhelps match one request to its logs. The method returns time still available, not the configured timeout. These values are illustrative; local tests pass None because the price code does not need context.
Ravindra Bagale's Tip
Keep calculation code independent of context where possible.
शक्य असेल तिथे calculation code context शिवाय चालेल असा ठेवा.
जहाँ हो सके calculation code context से अलग रखो.
Did you understand? Let us try it once more.