首页 > 解决方案 > 无法使用 python 将数据插入 dynamodb

问题描述

我是无服务器框架的新手,我正在尝试使用 python 将数据放入我的 dynamodb 中。但无法插入数据。即使我没有收到任何错误。

我已经尝试了 .yml 文件的所有设置,但没有任何进展

.yml

provider:
  name: aws
  runtime: python3.7

  environment:
    DYNAMODB_TABLE: employee
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"

  stage: dev
  region: us-east-1


functions:
   create:
    handler: functions/create.create
    events:
     - http:
         path: employee
         method: post
         cors: true
         authorizer: aws_iam
   get:
    handler: functions/get.get
    events:
     - http:
         path: employee/{id}
         method: get
         cors: true
         authorizer: aws_iam

resources:
  Resources:
    employee:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          - AttributeName: employeeId
            AttributeType: S
        KeySchema:
          - AttributeName: employeeId
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}

.py 文件

import json
import os
import logging

import boto3
dynamodb = boto3.resource('dynamodb')

logger = logging.getLogger("handler_logger")
logger.setLevel(logging.DEBUG)

def create(event, context):
    data = json.loads(event['body'])

    table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
    logger.info(table)

    item = {
        'employeeId': "2",
        'employeeName': "Singhs",
    }

    # write the todo to the database
    table.put_item(Item=item)

    # create a response
    response = {
        "statusCode": 200,
        "body": json.dumps(item)
    }

    return response

标签: pythonamazon-web-servicesamazon-dynamodbserverless

解决方案


我不确定为什么插入不起作用,代码看起来正确。如果您得到回复,您可以获得更多信息put_item。例如:

    # write the todo to the database
    put_response = table.put_item(Item=item)

    # create a response
    response = {
        "statusCode": 200,
        "body": json.dumps(put_response)
    }

推荐阅读