简体   繁体   English

如何导入boto3 athena客户端异常

[英]how to import boto3 athena client exceptions

I am working with athena from within my python code, using boto3, as follows:我在我的 python 代码中使用 athena,使用 boto3,如下所示:

def query_athena(query, output_path):
    client = boto3.client('athena')
    client.start_query_execution(
        ResultConfiguration={'OutputLocation': output_path},
        QueryString=query
    )

As stated in the docs , start_query_execution may raise InternalServerException , InvalidRequestException or TooManyRequestsException .文档中所述, start_query_execution可能引发InternalServerExceptionInvalidRequestExceptionTooManyRequestsException I'd like to treat this as follows:我想按如下方式处理:

def query_athena(query, output_path):
    client = boto3.client('athena')
    try:
        client.start_query_execution(
            ResultConfiguration={'OutputLocation': output_path},
            QueryString=query
        )
    except <AthenaException> as e:
        deal with e

where <AthenaException> being one of the three exceptions I mentioned or, better yet, their superclass.其中<AthenaException>是我提到的三个异常之一,或者更好的是它们的超类。

My question is how do I import these exceptions?我的问题是如何导入这些异常? The docs show them as Athena.Client.exceptions.InternalServerException , but I can't seem to find this Athena.Client in any boto3 module.文档将它们显示为Athena.Client.exceptions.InternalServerException ,但我似乎无法在任何 boto3 模块中找到此 Athena.Client 。

I ran into the same confusion, but figured it out.我遇到了同样的困惑,但想通了。 The exceptions listed in the docs aren't internal to boto3, but rather contained in the response when boto3 throws a client error.文档中列出的异常不是 boto3 内部的,而是包含在 boto3 抛出客户端错误时的响应中。

My first shot at a solution looks like this.我的第一个解决方案看起来像这样。 It assumes you've handled s3 output location, a boto3 session, etc already:它假定您已经处理了 s3 output 位置、boto3 session 等:

import boto3
from botocore.exceptions import ClientError

try:
    client = session.client('athena')
    response = client.start_query_execution(
        QueryString=q,
        QueryExecutionContext={
            'Database': database
        },
        ResultConfiguration={
            'OutputLocation': s3_output,
        }
    )
    filename = response['QueryExecutionId']
    print('Execution ID: ' + response['QueryExecutionId'])

except ClientError as e:
    response = e.response
    code = response['Error']['Code']
    message = response['Error']['Message']
    if code == 'InvalidRequestException':
        print(f'Error in query, {code}:\n{message}')
        raise e
    elif code == 'InternalServerException':
        print(f'AWS {code}:\n{message}')
        raise e
    elif code == 'TooManyRequestsException':
        # Handle a wait, retry, etc here
        pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM