使用boto3从python代码执行Athena查询会显示错误“ botocore.errorfactory.InvalidRequestException”

时间:2019-03-08 07:31:28

标签: boto3 amazon-athena

我正在按照下面的给定代码使用boto3库执行Athena查询:

import boto3
client = boto3.client('athena')

def main():
    queryStart = client.start_query_execution(
        QueryString = 'SELECT * FROM <tablename>',
        QueryExecutionContext = {
            'Database': '<databasename>'
        },
        ResultConfiguration={
        'OutputLocation': 's3://<outputlocation>',
        'EncryptionConfiguration': {
            'EncryptionOption': 'SSE_S3'
        }
     }
    )
    queryExecution = client.get_query_results(QueryExecutionId=queryStart['QueryExecutionId'],MaxResults=10)
    prinnt(queryExecution)

在执行此简单代码时,出现错误:

  Traceback (most recent call last):
      File "readingathena.py", line 38, in <module>
      main()
      File "readingathena.py", line 33, in main
      for i in response_iterator:
      File "C:\Program Files\Python36\lib\site-packages\botocore\paginate.py", line 255, in __iter__
      response = self._make_request(current_kwargs)
      File "C:\Program Files\Python36\lib\site-packages\botocore\paginate.py", line 332, in _make_request
return self._method(**current_kwargs)
      File "C:\Program Files\Python36\lib\site-packages\botocore\client.py", line 357, in _api_call
      return self._make_api_call(operation_name, kwargs)
      File "C:\Program Files\Python36\lib\site-packages\botocore\client.py", line 661, in _make_api_call
      raise error_class(parsed_response, operation_name)
      botocore.errorfactory.InvalidRequestException: An error occurred (InvalidRequestException) when calling the GetQueryResults operation: Query has not yet finished. Current state: RUNNING

我想要实现的是将结果打印在控制台上,而不是将其存储在s3位置。

P.S尽管有错误,输出仍存储在S3存储桶中。但是无法使用功能“ get_query_results”

获得响应

2 个答案:

答案 0 :(得分:1)

在查询完成之前无法获取查询结果,即状态为SUCCEEDED。您必须使用get_query_execution API调用来轮询状态,直到状态为SUCCEEDED,然后才调用get_query_results

不幸的是,如果没有将结果存储在S3中,也无法获得结果。这是雅典娜的设计方式,没有办法解决。

答案 1 :(得分:0)

我遇到了这个问题,仅通过将策略“ AmazonS3FullAccess”添加到Lambda所使用的角色中来解决。