0Pricing
Serverless Backend with AWS Lambda & API Gateway · درس

أول دالة Lambda باستخدام Python

اكتب أول دالة AWS Lambda لك وانشرها باستخدام Python، مع تعلّم بنيتها الأساسية ونموذج تنفيذها

أول دالة Lambda باستخدام Python درس مجاني في 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 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Welcome to AWS Lambda!

Time for your first function. AWS Lambda is Function as a Service: upload code, and Lambda runs it with zero servers to provision.

Why Python for Lambda?

Python is a great Lambda runtime — readable, rich libraries, perfect for APIs, data processing, and automation. Beginner-friendly too.

The Lambda Handler Function

Every Lambda needs an entry point: the handler. Lambda calls it with two args — event (input data) and context (runtime info).

Your First Python Lambda

Here's a minimal "Hello World" Lambda. All your logic lives in lambda_handler — run it locally to feel the shape.

import json

def lambda_handler(event, context):
    # Your function's logic goes here
    message = "Hello from your first Lambda!"
    
    # Lambda functions typically return a dictionary
    return {
        'statusCode': 200,
        'body': json.dumps(message)
    }

# This block allows you to test your function locally
if __name__ == "__main__":
    # Simulate an empty event and context for a simple test
    mock_event = {}
    mock_context = None
    response = lambda_handler(mock_event, mock_context)
    print("Local Test Response:", response)

Understanding the 'event'

The event parameter carries the input that triggered your function, delivered as JSON and converted into a Python dict — an API call, an S3 upload, a queue message.

Code: Reading from the Event

Now read a name from the event, falling back to a default. Notice event.get('key', default) for safe access without KeyErrors.

import json

def lambda_handler(event, context):
    # Get 'name' from the event, or default to 'there'
    name = event.get('name', 'there') 
    message = f"Hello, {name} from Lambda!"
    
    return {
        'statusCode': 200,
        'body': json.dumps(message)
    }

# Local testing with different events
if __name__ == "__main__":
    mock_event_with_name = {"name": "CoddyKit User"}
    response_with_name = lambda_handler(mock_event_with_name, None)
    print("With name:", response_with_name)

    mock_event_no_name = {}
    response_no_name = lambda_handler(mock_event_no_name, None)
    print("Without name:", response_no_name)

The 'context' Object

The context object exposes runtime info like aws_request_id, function_name, and remaining execution time. Handy even if you skip it often.

Returning a Standard Response

When API Gateway triggers your function, it expects a specific shape: a statusCode and a body that's a JSON string. That's how the client gets a clean response.

Code: Complete API Response

Here's a fuller, API-ready response with a Content-Type header and structured JSON body. We fake a context for local testing.

import json

def lambda_handler(event, context):
    name = event.get('name', 'World')
    
    # Simulate a context object for local testing
    request_id = getattr(context, 'aws_request_id', 'local-test-id')

    response_message = f"Greetings, {name}! Your request ID is {request_id}."

    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': json.dumps({
            'message': response_message,
            'input_data': event # Echoing input for demonstration
        })
    }

# Local testing with a dummy context
if __name__ == "__main__":
    class MockContext:
        aws_request_id = 'mock-request-123'

    mock_event = {"name": "CoddyKit"}
    mock_context_obj = MockContext()
    response = lambda_handler(mock_event, mock_context_obj)
    print("Full API Response:", response)

How Lambda Executes Your Code

On each event, Lambda spins up (or reuses) a container, loads your code, calls the handler, runs it, and returns the result — then waits or shuts down.

Quick Check

Which of the following best describes the purpose of the event parameter in a Python Lambda handler function?

Recap: Your First Lambda!

Recap: Lambda runs code with no servers. The handler is your entry point, event carries input as a dict, context gives runtime info, and you return a status + JSON body.

الأسئلة الشائعة

هل درس «أول دالة Lambda باستخدام Python» مجاني؟

نعم — نص درس «أول دالة Lambda باستخدام Python» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Serverless Backend with AWS Lambda & API Gateway، انتقل إلى CoddyKit PRO. تتضمن دورة Serverless Backend with AWS Lambda & API Gateway 4 دروس في المجموع.

ماذا ستتعلم في «أول دالة Lambda باستخدام Python»؟

اكتب أول دالة AWS Lambda لك وانشرها باستخدام Python، مع تعلّم بنيتها الأساسية ونموذج تنفيذها تتمرن على 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 باستخدام Python»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Serverless Backend with AWS Lambda & API Gateway هذا؟

نعم. كل درس في Serverless Backend with AWS Lambda & API Gateway يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. ما هي البنية عديمة الخوادم؟
  2. نظرة عامة على خدمات AWS الأساسية
  3. أول دالة Lambda باستخدام Python
  4. فهم نموذج تنفيذ Serverless
← العودة إلى Serverless Backend with AWS Lambda & API Gateway