簡體   English   中英

通過 Lambda 運行 aws Athena 查詢:未定義錯誤名稱“response”

[英]Run aws Athena query by Lambda: error name 'response' is not defined

我創建了一個 AWS lambda function 和 python 3.9 來運行 Athena 查詢並獲取查詢結果

import time
import boto3

# create Athena client

client = boto3.client('athena')

# create Athena query varuable

query = 'select * from mydatabase.mytable limit 8'
DATABASE = 'mydatabase'
output='s3://mybucket/'

def lambda_handler(event, context):
    # Execution
    response = client.start_query_execution(
        QueryString=query,
        QueryExecutionContext={
            'Database': DATABASE
        },
        ResultConfiguration={
            'OutputLocation': output,
        }
    )
    
query_execution_id = response['QueryExecutionId']
    
time.sleep(10)
    
result = client.get_query_results(QueryExecutionId=query_execution_id)
    
for row in results['ResultSet']['Rows']:
    print(row)

我在測試時收到此錯誤消息“[ERROR] NameError:未定義名稱'response'”

您在lambda_handler function 中定義response變量。但您在全局 scope 中引用它,在 function 之外,此處:

query_execution_id = response['QueryExecutionId']

該變量未在該 scope 上定義,因此出現錯誤消息。 看來您可能只是缺少所有這些行的縮進:

query_execution_id = response['QueryExecutionId']
    
time.sleep(10)
    
result = client.get_query_results(QueryExecutionId=query_execution_id)
    
for row in results['ResultSet']['Rows']:
    print(row)

在 Python 縮進是語法 如果您希望這些行成為lambda_handler function 的一部分,那么它們需要有正確的縮進才能將它們放在 function 的 scope 中,如下所示:

def lambda_handler(event, context):
    # Execution
    response = client.start_query_execution(
        QueryString=query,
        QueryExecutionContext={
            'Database': DATABASE
        },
        ResultConfiguration={
            'OutputLocation': output,
        }
    )
    
    query_execution_id = response['QueryExecutionId']
    
    time.sleep(10)
    
    result = client.get_query_results(QueryExecutionId=query_execution_id)
    
    for row in results['ResultSet']['Rows']:
        print(row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM