Salta ai contenuti

Funzioni Lambda di Python

Il generatore di Python Lambda Function permette di aggiungere una funzione lambda a un progetto Python esistente.

Questo generatore crea un nuovo handler per lambda function Python con la configurazione dell’infrastruttura AWS CDK. Il backend generato utilizza AWS Lambda per il deployment serverless, con opzionale type-safety tramite il Parser di AWS Lambda Powertools. Configura AWS Lambda Powertools per l’osservabilità, inclusi logging, tracciamento AWS X-Ray e metriche Cloudwatch.

Utilizzo

Genera una Lambda Function

Puoi generare una nuova Lambda Function in due modi:

  1. Installa il Nx Console VSCode Plugin se non l'hai già fatto
  2. Apri la console Nx in VSCode
  3. Clicca su Generate (UI) nella sezione "Common Nx Commands"
  4. Cerca @aws/nx-plugin - py#lambda-function
  5. Compila i parametri richiesti
    • Clicca su Generate

    Opzioni

    Parametro Tipo Predefinito Descrizione
    project Obbligatorio string - The project to add the lambda function to
    functionName Obbligatorio string - The name of the function to add
    functionPath string - The path within the project source directory to add the function to
    eventSource Obbligatorio string Any Optional event source model to use for the lambda function

    Output del Generatore

    Il generatore aggiungerà i seguenti file al tuo progetto:

    • Directory<module-name>
      • <lambda-function>.py Implementazione della funzione

    Il generatore creerà anche costrutti CDK utilizzabili per il deployment della funzione, residenti nella directory packages/common/constructs.

    Se viene fornita l’opzione functionPath, il generatore aggiungerà i file necessari al percorso specificato:

    • Directory<module-name>
      • Directory<custom-path>
        • <function-name>.py Implementazione della funzione

    Implementazione della Funzione

    L’implementazione principale della funzione si trova in <function-name>.py. Ecco un esempio:

    import os
    from aws_lambda_powertools import Logger, Metrics, Tracer
    from aws_lambda_powertools.metrics import MetricUnit
    from aws_lambda_powertools.utilities.parser import event_parser
    from aws_lambda_powertools.utilities.parser.models import EventBridgeModel
    from aws_lambda_powertools.utilities.typing import LambdaContext
    os.environ["POWERTOOLS_METRICS_NAMESPACE"] = "Foo"
    os.environ["POWERTOOLS_SERVICE_NAME"] = "Foo"
    logger: Logger = Logger()
    metrics: Metrics = Metrics()
    tracer: Tracer = Tracer()
    @tracer.capture_lambda_handler
    @metrics.log_metrics
    @event_parser(model=EventBridgeModel)
    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    logger.info("Received event", extra={"event": event.model_dump() })
    metrics.add_metric(name="InvocationCount", unit=MetricUnit.Count, value=1)
    try:
    # TODO: Implement
    metrics.add_metric(name="SuccessCount", unit=MetricUnit.Count, value=1)
    # TODO: Implement success response if required
    except Exception as e:
    logger.exception(e)
    metrics.add_metric(name="ErrorCount", unit=MetricUnit.Count, value=1)
    # TODO: Implement error response if required

    Il generatore configura automaticamente diverse funzionalità:

    1. Integrazione con AWS Lambda Powertools per l’osservabilità
    2. Raccolta delle metriche
    3. Type-safety usando @event_parser

    Osservabilità con AWS Lambda Powertools

    Logging

    Il generatore configura il logging strutturato usando AWS Lambda Powertools.

    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    logger.info("Received event", extra={"event": event.model_dump()})

    Il logger include automaticamente:

    • Richieste degli eventi
    • Informazioni sul contesto Lambda
    • Indicatori di cold start

    Tracing

    Il tracciamento AWS X-Ray è configurato automaticamente. Puoi aggiungere sottosegmenti personalizzati:

    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    # Crea un nuovo sottosegmento
    with tracer.provider.in_subsegment("function-subsegment"):
    # Logica personalizzata
    return ....

    Metriche

    Le metriche CloudWatch vengono raccolte automaticamente per ogni richiesta. Puoi aggiungere metriche personalizzate:

    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    metrics.add_metric(name="NewMetric", unit=MetricUnit.Count, value=1)
    return ...

    Le metriche predefinite includono:

    • Conteggi delle invocazioni
    • Metriche di successo/fallimento
    • Metriche sui cold start

    Type Safety

    Se hai selezionato un eventSource durante la generazione della funzione, questa sarà strumentata con @event_parser di AWS Lambda Powertools. Esempio:

    @event_parser(model=EventBridgeModel)
    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    event.detail_type # <- type-safe con autocompletamento IDE

    Questo permette di definire modelli dati usando Pydantic, in modo simile al lavoro con Fast API.

    Se non vuoi tipizzare l’evento, puoi selezionare Any come eventSource.

    Deployment della Funzione

    Il generatore crea un costrutto CDK per il deployment nella cartella common/constructs. Puoi utilizzarlo in un’applicazione CDK:

    import { MyProjectMyFunction } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // Aggiungi la funzione allo stack
    const fn = new MyProjectMyFunction(this, 'MyFunction');
    }
    }

    Questa configurazione include:

    1. Funzione AWS Lambda
    2. Log group CloudWatch
    3. Configurazione tracciamento X-Ray
    4. Namespace per metriche CloudWatch

    La funzione può quindi essere usata come target per qualsiasi event source lambda:

    L’esempio seguente mostra il codice CDK per invocare la funzione su una schedule usando Event Bridge:

    import { EventPattern, Rule, Schedule } from 'aws-cdk-lib/aws-events';
    import { LambdaFunction } from 'aws-cdk-lib/aws-events-targets';
    import { MyProjectMyFunction } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // Aggiungi la funzione allo stack
    const fn = new MyProjectMyFunction(this, 'MyFunction');
    // Aggiungi la funzione a una regola EventBridge
    const eventRule = new Rule(this, 'MyFunctionScheduleRule', {
    schedule: Schedule.cron({ minute: '15' }),
    targets: [new LambdaFunction(fn)],
    });
    }
    }