[英]Run aws Athena query by Lambda: error name 'response' is not defined
I create an AWS lambda function with python 3.9 to run the Athena query and get the query result我创建了一个 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)
I get this error message when I test it "[ERROR] NameError: name 'response' is not defined"我在测试时收到此错误消息“[ERROR] NameError:未定义名称'response'”
You define the response
variable inside the lambda_handler
function. But you are referencing it in the global scope, outside of that function, here:您在
lambda_handler
function 中定义response
变量。但您在全局 scope 中引用它,在 function 之外,此处:
query_execution_id = response['QueryExecutionId']
The variable isn't defined on that scope, thus the error message.该变量未在该 scope 上定义,因此出现错误消息。 It appears that you may simply be missing indentation on all these lines:
看来您可能只是缺少所有这些行的缩进:
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)
In Python indentation is syntax !在 Python 缩进是语法! If you intend those lines to be part of the
lambda_handler
function, then they need to have the correct indentation to place them inside the scope of the function, like so:如果您希望这些行成为
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.