boto3 资源不断出现“无法访问属性“表””

问题描述 投票:0回答:1

我正在学习 AWS Lambda,我们需要使用一段 Python 代码,它正在使用 boto3,但是当我将代码粘贴到代码编辑器中时,它立即给我一个错误。竞争错误是这样的:

Cannot access attribute "Table" for class "_"  Attribute "Table" is unknown

代码本身是这样的:

import boto3
table_name = "lambda-apigateway"
dynamo = boto3.resource('dynamodb').Table(table_name) -- ERROR IS HERE

需要注意的是,当我将代码粘贴到 VScode 中时,错误消失了,也许是因为我使用了不同的 Lsp?如果您能提供帮助,谢谢,这也是我的第一篇文章,因此我们将不胜感激将一些反馈纳入我未来的文章中。

这是完整的代码片段:

import boto3

# Define the DynamoDB table that Lambda will connect to
table_name = "lambda-apigateway"

# Create the DynamoDB resource
dynamo = boto3.resource('dynamodb').Table(table_name)

# Define some functions to perform the CRUD operations
def create(payload):
    return dynamo.put_item(Item=payload['Item'])

def read(payload):
    return dynamo.get_item(Key=payload['Key'])

def update(payload):
    return dynamo.update_item(**{k: payload[k] for k in ['Key', 'UpdateExpression', 
    'ExpressionAttributeNames', 'ExpressionAttributeValues'] if k in payload})

def delete(payload):
    return dynamo.delete_item(Key=payload['Key'])

def echo(payload):
    return payload

operations = {
    'create': create,
    'read': read,
    'update': update,
    'delete': delete,
    'echo': echo,
}

def lambda_handler(event, context):
    '''Provide an event that contains the following keys:
      - operation: one of the operations in the operations dict below
      - payload: a JSON object containing parameters to pass to the 
        operation being performed
    '''
    
    operation = event['operation']
    payload = event['payload']
    
    if operation in operations:
        return operations[operation](payload)
        
    else:
        raise ValueError(f'Unrecognized operation "{operation}"')

以及我当前正在关注的教程:https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway-tutorial.html#services-apigateway-tutorial-prereqs

我希望代码不会出现错误,但我不确定无论我做什么,该错误是否都会出现。

python amazon-web-services aws-lambda boto3
1个回答
0
投票

资源抽象似乎已被弃用。使用客户端抽象。

来源:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html

AWS Python SDK 团队并不打算向 boto3 中的资源接口。现有接口将继续 在 boto3 的生命周期内运行。客户可以找到更新的 通过客户端界面提供服务功能。

更换

dynamo = boto3.resource('dynamodb').Table(table_name) -- ERROR IS HERE

dynamo = boto3.client('dynamodb').Table(table_name)
© www.soinside.com 2019 - 2024. All rights reserved.