Ravindra BagaleCourses & study guides मराठी

Chapter 93: AWS Lambda and Serverless for DevOps

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.

Handlers, events and context
Handlers, events and context

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

  1. Put the handler in price.py.

  2. Use the same two argument names in local tests.

  3. Do not assume a fake local context has real AWS metadata.

Example 1: Read a tiny handler

  1. Read the input and the code.
def lambda_handler(event, context):
    total = event['qty'] * event['unit_paise']
    return {'total_paise': total, 'currency': 'INR'}
  1. Read the result.

Output (illustrative; not executed on AWS)

{'total_paise': 12000, 'currency': 'INR'}
  1. What each part means: def declares the entry function. The next line reads input fields and multiplies them. return makes a dictionary that the runtime can serialize. Handler setting price.lambda_handler means file price.py, function lambda_handler. Input validation is added in the local lab.

Example 2: Context is not the event

  1. 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()}
  1. Read the result.

Output (illustrative; not executed on AWS)

{'request_id': 'demo-request-1', 'remaining_ms': 2800}
  1. What each part means: aws_request_id helps 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.

Did you understand? Let us try it once more.