Problema durante l'esecuzione di script Python sulla funzione AWS Lambda

Aug 26 2020

Ho provato a eseguire lo script seguente su AWS Lambda, ma sfortunatamente non viene eseguito correttamente. Qualcuno può aiutarmi a ottenere questa correzione o correggermi se c'è un problema con lo script che necessita di alcune modifiche eseguendolo da Lambda?

#!/usr/bin/env python3
import boto3
client = boto3.client('athena')
def run_query(query, database, s3_output):
    response = client.start_query_execution(
        QueryString=query,
        QueryExecutionContext={
            'Database': 'database'
            },
        ResultConfiguration={
            'OutputLocation': s3_output,
            }
        )
    print('Execution ID: ' + response['QueryExecutionId'])
    return response     
  
#Athena configuration
s3_input = 's3://smathena/cf-ant-prod/'
s3_ouput = 's3://smathena/athenatest/'
database = 's3_accesslog'
table = 'test_output1'

#Athena database and table definition
create_database = "CREATE DATABASE IF NOT EXISTS %s;" % (database)
delete_table = "drop table %s.%s;" % ( database, table )
create_table = \
  """CREATE EXTERNAL TABLE IF NOT EXISTS %s.%s (
  `Date` DATE,
   ScContentLen BIGINT,
   ScRangeStart BIGINT,
   ScRangeEnd BIGINT
   )
   ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
   LOCATION '%s'
   TBLPROPERTIES ('skip.header.line.count' = '2');""" % ( database, table, s3_input )

#Query definitions
query_1 = "SELECT * FROM %s.%s where CAST(status AS VARCHAR) like '404';" % (database, table)

#Execute all queries
queries = [ create_database, delete_table, create_table, query_1 ]
for q in queries:
   print("Executing query: %s" % (q))
   res = 'run_query(q, database, s3_ouput)'

Errore durante il test su AWS Lambda:

  Response:
{
  "errorMessage": "run_query() missing 1 required positional argument: 's3_output'",
  "errorType": "TypeError",
  "stackTrace": [
    "  File \"/var/runtime/bootstrap.py\", line 131, in handle_event_request\n    response = request_handler(event, lambda_context)\n"
  ]
}

ID richiesta: "2cb2175c-8838-470d-a8dd-efdf4c051312"

Log delle funzioni: START RequestId: 2cb2175c-8838-470d-a8dd-efdf4c051312 Versione: $ LATEST [ERROR] TypeError: run_query () mancante 1 argomento posizionale richiesto: 's3_output' Traceback (la chiamata più recente last): File "/ var / runtime /bootstrap.py ", riga 131, in handle_event_request response = request_handler (event, lambda_context) END RequestId: 2cb2175c-8838-470d-a8dd-efdf4c051312

import boto3
client = boto3.client('athena')
def run_query(event, context):
    response = client.start_query_execution(
        QueryString=query,
        QueryExecutionContext={
            'Database': 'database'
            },
        ResultConfiguration={
            'OutputLocation': s3_output,
            }
        )
    print('Execution ID: ' + response['QueryExecutionId'])
    return event  

Ottenere il seguente errore:

START RequestId: 55dbf703-f30c-4106-8873-c685f3d06e4d Versione: $ LATEST [ERROR] NameError: nome 's3_output' non è definito Traceback (la chiamata più recente per ultima): File "/var/task/lambda_function.py", riga 12 , in run_query 'OutputLocation': s3_output, END RequestId: 55dbf703-f30c-4106-8873-c685f3d06e4d REPORT RequestId: 55dbf703-f30c-4106-8873-c685f3d06e4d Durata: 14,30 ms Durata fatturata: 100 MB Memoria massima utilizzata Dimensione memoria: 128 ms : 75 MB Durata iniziale: 649.66 ms

Risposte

JohnRotenstein Aug 27 2020 at 11:06

Questo è lo stesso problema della tua domanda precedente: errore durante l'esecuzione di uno script python su AWS Lambda - Stack Overflow

Una funzione AWS Lambda ha questo formato:

import boto3

def lambda_handler(event, context):
    
    print(event)
    print(context)

Quando viene richiamata la funzione Lambda, chiama la lambda_handler()funzione. Il nome di questa funzione può essere modificato se lo si desidera, ma riceverà sempre quei due parametri in ingresso: eventecontext

A seconda di come viene richiamata la funzione Lambda, il contenuto di eventcontiene informazioni che vengono "passate" alla funzione Lambda. Per esempio:

  • Se la funzione viene richiamata da Amazon S3, contiene il nome del bucket e dell'oggetto che ha attivato l'evento
  • Se la funzione viene richiamata da Amazon SNS, contiene il messaggio che è stato inviato all'argomento SNS

Sembra che tu voglia utilizzare tre valori nella funzione: query, database, s3_output

Questi valori dovranno essere passati alla funzione Lambda attraverso qualsiasi mezzo venga richiamata la funzione Lambda. La funzione può quindi recuperare quei valori tramite il eventparametro.